简体   繁体   English

如何在python中简化for循环

[英]How to simplify a for loop in python

I have this piece of Python code that fills up a 2d matrix in a for loop 我有这段Python代码填充for循环中的2d矩阵

img=zeros((len(bins_x),len(bins_y)))

for i in arange(0,len(ix)):
   img[ix[i]][iy[i]]=dummy[i]

Is it possible to use a vectorial operation for the last two lines of code? 是否可以对最后两行代码使用矢量运算? Is there also something that might speed up the calculation? 还有什么东西可以加快计算速度吗?

如果是ix,我是索引序列:

img[ix, iy] = dummy

It might be useful to use numpy . 使用numpy可能很有用。 In particular, the reshape method might be useful. 特别是, 重塑方法可能很有用。 Here is an example (adapted from the second link): 这是一个例子(改编自第二个链接):

>>> import numpy as np
>>> a = np.array([1,2,3,4,5,6])
>>> np.reshape(a, (3,2))
array([[1, 2],
       [3, 4],
       [5, 6]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM