以此为本,以此为本,以此为本,以此为本,以此为本,以此为本,以此为本。
如果您的列表来自列表理解,问题可以通过纠正理解更简单/直接解决;请参见Python列表理解;压缩列表?
在这里,最受欢迎的解决方案通常只包含一个“层”的清单。 查看清单不规则(自愿清单)的清单,解决方案完全清单一个深度清单的结构(重复,一般)。
以此为本,以此为本,以此为本,以此为本,以此为本,以此为本,以此为本。
如果您的列表来自列表理解,问题可以通过纠正理解更简单/直接解决;请参见Python列表理解;压缩列表?
在这里,最受欢迎的解决方案通常只包含一个“层”的清单。 查看清单不规则(自愿清单)的清单,解决方案完全清单一个深度清单的结构(重复,一般)。
当前回答
我会建议使用发电机与产量声明和产量从。
from collections.abc import Iterable
def flatten(items, ignore_types=(bytes, str)):
"""
Flatten all of the nested lists to the one. Ignoring flatting of iterable types str and bytes by default.
"""
for x in items:
if isinstance(x, Iterable) and not isinstance(x, ignore_types):
yield from flatten(x)
else:
yield x
values = [7, [4, 3, 5, [7, 3], (3, 4), ('A', {'B', 'C'})]]
for v in flatten(values):
print(v)
其他回答
您也可以使用NumPy的公寓:
import numpy as np
list(np.array(l).flat)
它只有在超级列表具有相同的尺寸时才有效。
我会建议使用发电机与产量声明和产量从。
from collections.abc import Iterable
def flatten(items, ignore_types=(bytes, str)):
"""
Flatten all of the nested lists to the one. Ignoring flatting of iterable types str and bytes by default.
"""
for x in items:
if isinstance(x, Iterable) and not isinstance(x, ignore_types):
yield from flatten(x)
else:
yield x
values = [7, [4, 3, 5, [7, 3], (3, 4), ('A', {'B', 'C'})]]
for v in flatten(values):
print(v)
考虑安装 more_itertools 包。
> pip install more_itertools
它配备了一个应用程序为平板(来源,从 itertools 食谱):
import more_itertools
lst = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
list(more_itertools.flatten(lst))
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
注意:正如文件中提到的那样,平板需要列表。 查看下面的平板更多不规则输入。
至于版本 2.4,您可以用更多_itertools.collapse (来源,由abarnet 贡献) 插入更复杂、更精致的 iterables。
lst = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
list(more_itertools.collapse(lst))
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
lst = [[1, 2, 3], [[4, 5, 6]], [[[7]]], 8, 9] # complex nesting
list(more_itertools.collapse(lst))
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
对于包含多个列表的列表,这里是一个重复的解决方案,为我工作,我希望它是正确的:
# Question 4
def flatten(input_ls=[]) -> []:
res_ls = []
res_ls = flatten_recursive(input_ls, res_ls)
print("Final flatten list solution is: \n", res_ls)
return res_ls
def flatten_recursive(input_ls=[], res_ls=[]) -> []:
tmp_ls = []
for i in input_ls:
if isinstance(i, int):
res_ls.append(i)
else:
tmp_ls = i
tmp_ls.append(flatten_recursive(i, res_ls))
print(res_ls)
return res_ls
flatten([0, 1, [2, 3], 4, [5, 6]]) # test
flatten([0, [[[1]]], [[2, 3], [4, [[5, 6]]]]])
出口:
[0, 1, 2, 3]
[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6]
Final flatten list solution is:
[0, 1, 2, 3, 4, 5, 6]
[0, 1]
[0, 1]
[0, 1]
[0, 1, 2, 3]
[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6]
Final flatten list solution is:
[0, 1, 2, 3, 4, 5, 6]
如果你想清理一切,并保持一个单独的元素列表,你也可以使用它。
list_of_lists = [[1,2], [2,3], [3,4]]
list(set.union(*[set(s) for s in list_of_lists]))