简体   繁体   English

1 行中的双 for 循环以创建新的元组列表

[英]Double for loop in 1 line to create a new tuple list

I have two sets of coordinates as numpy array.我有两组坐标作为 numpy 数组。 I would to create a new coordinate based on the first element of each set.我会根据每个集合的第一个元素创建一个新坐标。

a = np.array([[1,2],[3,4],[5,6]])
b = np.array([[10,20],[30,40],[50,60]])

so I would like to get所以我想得到

[(1,10), (3,30), (5, 50)] [(1,10), (3,30), (5, 50)]

I tried:我试过:

c = [(i[0], j[0]) for (i,j) in itertools.product(a,b)]

But itreturned:但它返回:

[(1, 10), (1, 30), (1, 50), (3, 10), (3, 30), (3, 50), (5, 10), (5, 30), (5, 50)] [(1, 10), (1, 30), (1, 50), (3, 10), (3, 30), (3, 50), (5, 10), (5, 30), ( 5, 50)]

which is a nested loop.这是一个嵌套循环。 Is there a one line solution here?这里有单行解决方案吗?

Many thanks非常感谢

J J

If you want result as tuples, first concatenate them along the second axis with np.c_ , view the result as an array of tuples and flatten the result with ravel :如果你想结果作为元组中,首先将它们连接起来沿着与所述第二轴线np.c_ ,查看结果作为元组的阵列,并且变平,结果ravel

np.c_[a[:,0],b[:,0]].view('i,i').ravel()
# array([(1, 10), (3, 30), (5, 50)], dtype=[('f0', '<i4'), ('f1', '<i4')])

Note that obtaining the result using numpy's vectorized operations will lead to huge benefits in terms of performance:请注意,使用 numpy 的矢量化操作获得结果将在性能方面带来巨大的好处:

a = np.array([[1,2],[3,4],[5,6]])
b = np.array([[10,20],[30,40],[50,60]])
a = np.concatenate([a]*10000)
b = np.concatenate([b]*10000)

%timeit [(a_s[0], b_s[0]) for a_s, b_s in zip(a,b)]
# 19.2 ms ± 1.5 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit np.c_[a[:,0],b[:,0]].view('i,i').ravel()
# 82.1 µs ± 7.73 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Try the built-in function zip :试试内置函数zip

print([(a_s[0], b_s[0]) for a_s, b_s in zip(a,b)])
# [(1, 10), (3, 30), (5, 50)]
temp_arr = np.concatenate([a[:,:,None],b[:,:,None]],axis=2)
temp_arr[:,0]
array([[ 1, 10],
       [ 3, 30],
       [ 5, 50]])

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

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