合并三个列表成一个列表

22 浏览
0 Comments

合并三个列表成一个列表

这个问题已经有答案了

如何将列表中的列表转成一个平面列表?

嗨,我有三个列表,如下:

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]

admin 更改状态以发布 2023年5月21日
0
0 Comments

您可以使用numpy实现该功能。

import numpy as np
a = [1,2,3,4]
b = [2,3,4,5]
c = [3,4,5,6]
d = np.array([a, b, c]).flatten('F')  # -> [1 2 3 2 3 4 3 4 5 4 5 6]

0
0 Comments

你可以使用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]

0