Python List None操作

对于类似C[:,None,:]的操作,等价于在C中插入一个维度,插入维度的位置在第None所在的位置

类似于torch中的unsqueeze操作

import torch
import numpy as np
c = np.random.rand(1,2,3,4)
print(c.shape)
d = np.sum(c,2)
print(c,)
print("  ")
print("  ")
print(d,)
print(d.shape)
print(c/d[:,:,None,:])

c = torch.tensor(c)
d = torch.tensor(d)
print("\r\r")
print(c/(d.unsqueeze(2)))

运行结果如图

(1, 2, 3, 4)
[[[[0.45248524 0.69574824 0.57580697 0.1842294 ]
   [0.44627855 0.1023007  0.27848436 0.98385908]
   [0.54614187 0.55921776 0.54211003 0.47797798]]

  [[0.60861482 0.76155085 0.27411051 0.68374115]
   [0.80567721 0.93184501 0.02891797 0.54246101]
   [0.173862   0.87481428 0.84554342 0.26778267]]]]
  
  
[[[1.44490567 1.3572667  1.39640136 1.64606646]
  [1.58815402 2.56821014 1.1485719  1.49398483]]]
(1, 2, 4)
[[[[0.31315902 0.51260982 0.41235062 0.111921  ]
   [0.30886345 0.07537258 0.19943003 0.59770313]
   [0.37797753 0.41201759 0.38821935 0.29037587]]

  [[0.38322153 0.2965298  0.23865333 0.45766271]
   [0.5073042  0.3628383  0.02517733 0.36309673]
   [0.10947427 0.34063189 0.73616934 0.17924055]]]]

tensor([[[[0.3132, 0.5126, 0.4124, 0.1119],
          [0.3089, 0.0754, 0.1994, 0.5977],
          [0.3780, 0.4120, 0.3882, 0.2904]],

         [[0.3832, 0.2965, 0.2387, 0.4577],
          [0.5073, 0.3628, 0.0252, 0.3631],
          [0.1095, 0.3406, 0.7362, 0.1792]]]], dtype=torch.float64)

你可能感兴趣的:(python,1024程序员节,python,numpy)