[英]Combine 2d-array into tuple
I want to combine two 2d-arrays into one NX2 array, but I don't know what command should I use in python. For example, a = [1.2.3] b = [4,5,6]
, and I want to have a new array which have the elements in a as the x-coordinate and b as the y-coordinate, c = [(1,4)],(2,5),(3,6)]
我想将两个二维数组组合成一个 NX2 数组,但我不知道在 python 中应该使用什么命令。例如,
a = [1.2.3] b = [4,5,6]
,我想要有一个新的数组,其中 a 中的元素作为 x 坐标,b 中的元素作为 y 坐标, c = [(1,4)],(2,5),(3,6)]
Any hint for this in python language? python 语言对此有任何提示吗?
You're lucky, because Python has a built-in zip
function that does exactly what you want. 你很幸运,因为Python有一个内置的
zip
功能,完全符合你的要求。
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> zip(a, b)
[(1, 4), (2, 5), (3, 6)]
Note that in Python 3, zip
returns an iterator, not a list, so you will have to use list(zip(a, b))
to get a list. 请注意,在Python 3中,
zip
返回迭代器而不是列表,因此您必须使用list(zip(a, b))
来获取列表。
Also note that zip
truncates the length of the result to the smallest list. 另请注意,
zip
会将结果的长度截断为最小的列表。
For example: 例如:
>>> zip([1, 2], [3, 4, 5])
[(1, 3), (2, 4)]
You can combat this with itertools.izip_longest
(or itertools.zip_longest
in Python 3). 您可以使用
itertools.izip_longest
(或Python 3中的itertools.zip_longest
)来解决这个问题。
>>> import itertools
>>> list(itertools.izip_longest([1, 2], [3, 4, 5], fillvalue=0))
[(1, 3), (2, 4), (0, 5)]
This will use the fillvalue
to fill in the empty gaps. 这将使用
fillvalue
填充空白。 By default, fillvalue
is set to None
. 默认情况下,
fillvalue
设置为None
。
You can use the zip function.您可以使用 zip function。
x = [1,2,3,4]
y = [1,2,3,4]
nodes = [zip(x,y)]
Use zip() inside list() to get the list.在 list() 中使用 zip() 来获取列表。 Or else it will print as,
否则它将打印为,
[<zip object at 0x0000024AE84502C0>]
Do it i this way instead我改为这样做
nodes = list(zip(x,y))
It is going to print它要打印
[(1, 1), (2, 2), (3, 3), (4, 4)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.