以特定方式将两个列表追加到一个列表



假设,我有两个列表:

[a, b] and [c,d]

如何在 Python 中获取以下数组作为结果?

[a, c]
[b, d]

压缩这些列表。

list(map(list, zip(list1,list2)))

空闲输出:

>>> list1 = [1,2]
>>> list2 = [10,11]
>>> list(map(list, zip(list1,list2)))
[[1, 10], [2, 11]]

Numpy 解决方案:

import numpy as np
a = [1, 2]
b = [3, 4]
joint_array = np.asarray((a, b)).T

由于您在评论中特别提到您不想要列表列表,而是两个列表的串联:

[a,b]+[c,d]

结果将是 [a,b,c,d]

否则,如果这不是您想要的,Gauri 或 user2653663 的答案可能是您想要的。

如果您打算使用按列串联创建两个新的列表变量,则可以这样做:

list1 = ["a", "b"]
list2 = ["c", "d"]
list3,list4 = [list(z) for z in zip(list1,list2)]
print(list3) 
print(list4) 
# ['a', 'c']
# ['b', 'd']