gpt4 book ai didi

python - 如何取消嵌套嵌套列表

转载 作者:IT老高 更新时间:2023-10-28 21:53:09 26 4
gpt4 key购买 nike

Possible Duplicate:
Making a flat list out of list of lists in Python

我正在尝试找到一种简单的方法将多维(嵌套)python 列表转换为单个列表,其中包含子列表的所有元素。

例如:

A = [[1,2,3,4,5]]

转向

A = [1,2,3,4,5]

A = [[1,2], [3,4]]

转向

A = [1,2,3,4]

最佳答案

使用 itertools.chain :

itertools.chain(*iterables):

Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. Used for treating consecutive sequences as a single sequence.

Example:

from itertools import chain

A = [[1,2], [3,4]]

print list(chain(*A))
# or better: (available since Python 2.6)
print list(chain.from_iterable(A))

输出是:

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

关于python - 如何取消嵌套嵌套列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11860476/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com