[英]How to zip each element from a 1D array with the elements from each row of a 2D array?
我正在尝试使用matplotlib
绘制数据集,其中每个x
包含多个y
坐标。 要绘制它们,我必须组合这些数组以在单个图中显示它们。 如何使用来自二维数组每一行的元素(对应于一维数组元素的索引)压缩一维数组中的每个元素? 不使用显式 for 循环。 使用内置函数(例如 zip/list comprehension)甚至更好: numpy
?
转向:
x = [1, 2, 3]
y = [[4, 5], [6, 7], [8, 9]]
进入:
r = [(1, 4), (1, 5), (2, 6), (2, 7), (3, 8), (3, 9)]
我想到了以下几点:
将x
扩展为与y
相同的大小
压平y
压缩x
和y
如下
>>> x = [1, 2, 3]
>>> y = [[4, 5], [6, 7], [8, 9]]
>>> x = np.array(x).repeat(2)
>>> y = np.array(y).reshape(-1)
>>> list(zip(x, y))
[(1, 4), (1, 5), (2, 6), (2, 7), (3, 8), (3, 9)]
我很想知道如何更有效地做到这一点。
请评论或回答更有效的方法。
x = [1, 2, 3]
y = [[4, 5], [6, 7], [8, 9]]
result = [(i[0], i[1][0]) for i in zip(x,y)] + [(i[0], i[1][1]) for i in zip(x,y)]
输出:
[(1, 4), (2, 6), (3, 8), (1, 5), (2, 7), (3, 9)]
通过方法5启发这里:
from functools import reduce
x = [1, 2, 3]
y = [[4, 5], [6, 7], [8, 9]]
def listOfTuples(l1, l2):
l = list(map(lambda x, y:[(x,y[0]), (x,y[1])], l1, l2))
m = reduce(lambda x, y: x + y, l)
return(m)
r = listOfTuples(x, y)
给
[(1, 4), (1, 5), (2, 6), (2, 7), (3, 8), (3, 9)]
repeat
和reshape
方法的变体:
In [89]: x = [1, 2, 3]
...: y = [[4, 5], [6, 7], [8, 9]]
In [90]: res = np.zeros((3,2,2),int)
In [91]: res[:,:,1]=y
In [92]: res[:,:,0]=np.array(x)[:,None]
In [93]: res
Out[93]:
array([[[1, 4],
[1, 5]],
[[2, 6],
[2, 7]],
[[3, 8],
[3, 9]]])
In [94]: res.reshape(6,2)
Out[94]:
array([[1, 4],
[1, 5],
[2, 6],
[2, 7],
[3, 8],
[3, 9]])
它使用broadcasting
将x
和y
映射到res
数组。
这仅使用迭代器,使用itertools.chain.from_iterable
import itertools
x = [1, 2, 3]
y = [[4, 5], [6, 7], [8, 9]]
list(zip(list(itertools.chain.from_iterable(itertools.repeat(n, 2) for n in x)),
list(itertools.chain.from_iterable(y))))
输出
[(1, 4), (1, 5), (2, 6), (2, 7), (3, 8), (3, 9)]
恕我直言,这在长期运行中应该更快。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.