合并嵌套列表,将列(同一索引中的元素)保持在一起

Merge nested lists keeping the column (elements at same index) together

我有一个列表列表:

lst = [
    [1,2,3],
    [1,2,3],
    [1,2,3]
]

我怎样才能将列表的每一列添加到一个空列表中。 我的意思是 lst[i][column],例如1,1,1 然后 2,2,2,等等,得到一个 new 列表,如下所示:

[1,1,1,2,2,2,3,3,3]

到目前为止我已经尝试过:

pos = 0
column = 0
row = 0
i = 0
empty = []
while i < len(lst):
    empty.append(lst[i][0])
    i += 1
print(empty)

以下是如何使用 nested list comprehension:

lst = [
    [1,2,3],
    [1,2,3],
    [1,2,3]
]

print([v[i] for i in range(len((lst[0]))) for v in lst])

输出:

[1, 1, 1, 2, 2, 2, 3, 3, 3]

上面的嵌套列表推导等价于这个nested for loop:

lst = [
    [1,2,3],
    [1,2,3],
    [1,2,3]
]

arr = list()
for i in range(len((lst[0]))):
    for v in lst:
        arr.append(v[i])
print(arr)

输出:

[1, 1, 1, 2, 2, 2, 3, 3, 3]

最后,你可以使用内置的zip()方法:

lst = [
    [1,2,3],
    [1,2,3],
    [1,2,3]
]

print([j for i in zip(*lst) for j in i])

这是通过使用 itertools.chain() and zip() 的组合实现此目的的实用方法:

from itertools import chain

my_list = [
    [1,2,3],
    [1,2,3],
    [1,2,3]
]

new_list = list(chain(*zip(*my_list)))

new_list 的位置:

[1, 1, 1, 2, 2, 2, 3, 3, 3]

请参阅以下链接以了解有关这些功能的更多信息:

您可以使用 itertools.chain and really work the star operator:

from itertools import chain

[*chain(*zip(*lst))]  
# or more classic:
# list(chain.from_iterable(zip(*lst)))
# [1, 1, 1, 2, 2, 2, 3, 3, 3]

或者在简单的嵌套理解中使用上面显示的换位模式zip(*...)

[x for sub in zip(*lst) for x in sub]
# [1, 1, 1, 2, 2, 2, 3, 3, 3]
lst = [
    [1,2,3],
    [1,2,3],
    [1,2,3]
]
new_list = []
for i,j in enumerate(lst):
    new = lst[i]
    new_list.extend(new)

new_list = sorted(new_list)

print(new_list)

输出:

[1, 1, 1, 2, 2, 2, 3, 3, 3]