首页 > 解决方案 > 将三个列表合并为 1 个列表

问题描述

嗨,我有三个这样的列表:

a = [1,2,3,4]
b = [2,3,4,5]
c = [3,4,5,6]

如何制作一个新列表,以便从所有列表中获取值。例如,它的前三个元素将是 1、2、3,因为它们是 a、b、c 的第一个元素。因此,它看起来像

d = [1,2,3,2,3,4,3,4,5,4,5,6]

标签: pythonarraysnumpy

解决方案


您可以使用zip

a = [1,2,3,4]
b = [2,3,4,5]
c = [3,4,5,6]

[item for sublist in zip(a, b, c) for item in sublist]
# [1, 2, 3, 2, 3, 4, 3, 4, 5, 4, 5, 6]

第一个 for 循环:

for sublist in zip(a, b, c)

将迭代由 提供的元组zip,这将是:

(1st item of a, 1st item of b, 1st item of c)
(2nd item of a, 2nd item of b, 2nd item of c)
...

第二个 for 循环:

for item in sublist

将迭代这些元组的每一项,构建最终列表:

[1st item of a, 1st item of b, 1st item of c, 2nd item of a, 2nd item of b, 2nd item of c ...]

要回答@bjk116 的评论,请注意理解中的for循环的编写顺序与您在普通叠层循环中使用的顺序相同:

out = []
for sublist in zip(a, b, c):
    for item in sublist:
        out.append(item)
print(out)
# [1, 2, 3, 2, 3, 4, 3, 4, 5, 4, 5, 6]

推荐阅读