以此为本,以此为本,以此为本,以此为本,以此为本,以此为本,以此为本。
如果您的列表来自列表理解,问题可以通过纠正理解更简单/直接解决;请参见Python列表理解;压缩列表?
在这里,最受欢迎的解决方案通常只包含一个“层”的清单。 查看清单不规则(自愿清单)的清单,解决方案完全清单一个深度清单的结构(重复,一般)。
以此为本,以此为本,以此为本,以此为本,以此为本,以此为本,以此为本。
如果您的列表来自列表理解,问题可以通过纠正理解更简单/直接解决;请参见Python列表理解;压缩列表?
在这里,最受欢迎的解决方案通常只包含一个“层”的清单。 查看清单不规则(自愿清单)的清单,解决方案完全清单一个深度清单的结构(重复,一般)。
当前回答
我创建了一点功能,基本上可以平滑任何东西. 你可以用管道:管道安装平滑一切
from flatten_everything import flatten_everything
withoutprotection=list(
flatten_everything(
[
1,
1,
2,
[3, 4, 5, [6, 3, [2, 5, ["sfs", "sdfsfdsf",]]]],
1,
3,
34,
[
55,
{"brand": "Ford", "model": "Mustang", "year": 1964, "yearxx": 2020},
pd.DataFrame({"col1": [1, 2], "col2": [3, 4]}),
{"col1": [1, 2], "col2": [3, 4]},
55,
{"k32", 34},
np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]),
(np.arange(22), np.eye(2, 2), 33),
],
]
)
)
print(withoutprotection)
output:
[1, 1, 2, 3, 4, 5, 6, 3, 2, 5, 'sfs', 'sdfsfdsf', 1, 3, 34, 55, 'Ford', 'Mustang', 1964, 2020, 1, 2, 3, 4, 1, 2, 3, 4, 55, 34, 'k32', 1, 2, 3, 4, 5, 6, 7, 8, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 1.0, 0.0, 0.0, 1.0, 33]
你甚至可以保护物体免受闪烁:
from flatten_everything import ProtectedDict,ProtectedList,ProtectedTuple
withprotection=list(
flatten_everything(
[
1,
1,
2,
[3, 4, 5, [6, 3, [2, 5, ProtectedList(["sfs", "sdfsfdsf",])]]],
1,
3,
34,
[
55,
ProtectedDict({"brand": "Ford", "model": "Mustang", "year": 1964, "yearxx": 2020}),
pd.DataFrame({"col1": [1, 2], "col2": [3, 4]}),
{"col1": [1, 2], "col2": [3, 4]},
55,
{"k32", 34},
np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]),
ProtectedTuple((np.arange(22), np.eye(2, 2), 33)),
],
]
)
)
print(withprotection)
output:
[1, 1, 2, 3, 4, 5, 6, 3, 2, 5, ['sfs', 'sdfsfdsf'], 1, 3, 34, 55, {'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'yearxx': 2020}, 1, 2, 3, 4, 1, 2, 3, 4, 55, 34, 'k32', 1, 2, 3, 4, 5, 6, 7, 8, (array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,17, 18, 19, 20, 21]), array([[1., 0.], [0., 1.]]), 33)]
其他回答
我用 perfplot 测试了大多数建议的解决方案(我的宠物项目,基本上是时间周围的插槽),并发现
import functools
import operator
functools.reduce(operator.iconcat, a, [])
要成为最快的解决方案,无论是许多小列表还是很少的长列表都被混合(operator.iadd 同样快)。
更简单、更可接受的选择是
out = []
for sublist in a:
out.extend(sublist)
如果字体列表的数量很大,这表现得比上面的建议略糟糕。
此分類上一篇
此分類上一篇
重复字符的代码:
import functools
import itertools
import operator
import numpy as np
import perfplot
def forfor(a):
return [item for sublist in a for item in sublist]
def sum_brackets(a):
return sum(a, [])
def functools_reduce(a):
return functools.reduce(operator.concat, a)
def functools_reduce_iconcat(a):
return functools.reduce(operator.iconcat, a, [])
def itertools_chain(a):
return list(itertools.chain.from_iterable(a))
def numpy_flat(a):
return list(np.array(a).flat)
def numpy_concatenate(a):
return list(np.concatenate(a))
def extend(a):
out = []
for sublist in a:
out.extend(sublist)
return out
b = perfplot.bench(
setup=lambda n: [list(range(10))] * n,
# setup=lambda n: [list(range(n))] * 10,
kernels=[
forfor,
sum_brackets,
functools_reduce,
functools_reduce_iconcat,
itertools_chain,
numpy_flat,
numpy_concatenate,
extend,
],
n_range=[2 ** k for k in range(16)],
xlabel="num lists (of length 10)",
# xlabel="len lists (10 lists total)"
)
b.save("out.png")
b.show()
考虑安装 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]
使用 functools.reduce,将积累的列表 xs 添加到下列列表 ys:
from functools import reduce
xss = [[1,2,3], [4,5,6], [7], [8,9]]
out = reduce(lambda xs, ys: xs + ys, xss)
出口:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
使用 operator.concat 的更快方法:
from functools import reduce
import operator
xss = [[1,2,3], [4,5,6], [7], [8,9]]
out = reduce(operator.concat, xss)
出口:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
您可以使用 itertools.chain():
>>> import itertools
>>> list2d = [[1,2,3], [4,5,6], [7], [8,9]]
>>> merged = list(itertools.chain(*list2d))
或者您可以使用 itertools.chain.from_iterable(),不需要与 * 运营商解包列表:
>>> import itertools
>>> list2d = [[1,2,3], [4,5,6], [7], [8,9]]
>>> merged = list(itertools.chain.from_iterable(list2d))
这种方法可能比 [分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类中的分类
$ python3 -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99;import itertools' 'list(itertools.chain.from_iterable(l))'
20000 loops, best of 5: 10.8 usec per loop
$ python3 -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' '[item for sublist in l for item in sublist]'
10000 loops, best of 5: 21.7 usec per loop
$ python3 -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' 'sum(l, [])'
1000 loops, best of 5: 258 usec per loop
$ python3 -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99;from functools import reduce' 'reduce(lambda x,y: x+y,l)'
1000 loops, best of 5: 292 usec per loop
$ python3 --version
Python 3.7.5rc1
根據您的列表(1, 2, 3), [4, 5, 6], [7], [8, 9] 是 1 列表水平,我們可以簡單地使用數量(列表),而不使用任何圖書館。
sum([[1, 2, 3], [4, 5, 6], [7], [8, 9]],[])
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
延伸此方法的优势,当内部存在一个<unk>或数字时,简单地将每个元素的地图函数添加到列表中
#For only tuple
sum(list(map(list,[[1, 2, 3], (4, 5, 6), (7,), [8, 9]])),[])
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
#In general
def convert(x):
if type(x) is int or type(x) is float:
return [x]
else:
return list(x)
sum(list(map(convert,[[1, 2, 3], (4, 5, 6), 7, [8, 9]])),[])
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
在这里,有一个明确的解释的缺点在记忆的这个方法。 简而言之,它重复创建列表对象,应该避免( )