将三个列表合并为一个列表

时间:2019-12-20 14:27:26

标签: python arrays numpy

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

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]

4 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:2)

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

答案 2 :(得分:1)

这是leetcode 48旋转图像的替代版本,并添加了flatten ..仍然很简单:

mat = [a,b,c]
mat[::] = zip(*mat)
[item for sublist in mat for item in sublist]

答案 3 :(得分:1)

正如Thierry所指出的,我们需要使用$router->get('/', ['middleware' => 'auth.token.authenticate', function () use ($router) { // these routes will just have auth.token.authenticate applied }]); $router->get('/authenticate', ['middleware' => 'auth.token|auth.token.authenticate', function () use ($router) { // these routes will have both auth.token and auth.token.authenticate applied, with auth.token being the first one }]); 来转置列表,并串联一个新列表。

这是使用内置软件包zip(a,b,c)进行操作的非常快的方式(在性能和代码可读性方面):

itertools

或者,不使用参数解包:

from itertools import chain
result = list(chain(*zip(a,b,c)))

这很经典。但是,令人惊讶的是,Python还有另一个名为more_itertools的软件包,该软件包有助于进行更高级的迭代。您需要安装并使用:

result = list(chain.from_iterable(zip(a,b,c)))