如何将两个维度列表组合到python中的点列表中

Ahm*_*mad -1 python list

假设我有:

x1 = [1, 2, 3, 4]
x2 = [1, 4, 9, 16]
Run Code Online (Sandbox Code Playgroud)

我如何将它们组合到点:

points = [[1,1],[2,4], ...]
Run Code Online (Sandbox Code Playgroud)

tim*_*geb 6

你在找zip.

>>> X1 = [1, 2, 3, 4]
>>> X2 = [1, 4, 9, 16]
>>> 
>>> [list(pair) for pair in zip(X1, X2)]
>>> [[1, 1], [2, 4], [3, 9], [4, 16]]
Run Code Online (Sandbox Code Playgroud)

如果没有特别的理由让元素成为列表,那么只需单独使用zip它来生成元组的迭代器(Python 3)或列表(Python 2).

>>> list(zip(X1, X2)) # or just zip(X1, X2) in Python 2
>>> [(1, 1), (2, 4), (3, 9), (4, 16)]
Run Code Online (Sandbox Code Playgroud)

如果你甚至不需要同时在内存中使用所有这些对,例如,如果你想做的只是迭代它们,不要构建一个列表.在Python 3中,zip生成一个迭代器.

>>> pairs = zip(X1, X2)
>>> for pair in pairs:
...:    print(pair)
...:    
(1, 1)
(2, 4)
(3, 9)
(4, 16)
>>> 
>>> pairs = zip(X1, X2)
>>> next(pairs)
>>> (1, 1)
>>> next(pairs)
>>> (2, 4)
Run Code Online (Sandbox Code Playgroud)

最后,如果你想zip在Python 2中使用Python 3 ,请使用izipfrom itertools.