[英]How to use reduce with list of lists
以下是什么问题?:
lss = reduce(list.extend, [[1],[2]], [])
原因:
Traceback (most recent call last):
File "<pyshell#230>", line 1, in <module>
lss = reduce(list.extend, [[1],[2]], [])
TypeError: descriptor 'extend' requires a 'list' object but received a 'NoneType'
我不确定NoneType
来自哪里。
我认为值得注意的是:
sum([[1],[2]], [])
也会工作,我很确定会比传递lambda更快更快。
我很好奇不同方法的速度,所以我做了一些测试:
reduce(lambda a,b:a+b, x, []) 3644.38161492
reduce(list.__add__, x, []) 3609.44079709
sum(x,[]) 3526.84987307
y = [];for z in x: y.extend(z) 143.370306969
y = [];map(y.extend,x) 71.7020270824
y = [None]*400;del y[:];map(y.extend,x) 66.2245891094
list(itertools.chain(*x)) 102.285979986
list(itertools.chain.from_iterable(x)) 96.6231369972
[a for b in x for a in b] 203.764872074
在PyPy上(因为,为什么不)
reduce(lambda a,b:a+b, x, []) 4797.5895648
reduce(list.__add__, x, []) 4794.01214004
sum(x,[]) 4748.02929902
y = [];for z in x: y.extend(z) 56.9253079891
y = [];map(y.extend,x) 73.8642170429
y = [None]*400;del y[:];map(y.extend,x) 152.157783031
list(itertools.chain(*x)) 633.854824066
list(itertools.chain.from_iterable(x)) 629.917827129
[a for b in x for a in b] 89.6922459602
x = [[1,2,3,4],[2,3,4,5],[3,4,5,6],[4,5,6,7],[5,6,7,8],[6,7,8,9],[7,8,9,10],[8,9,10,11]]*100
结论:
sum
函数更快然后减少 正如list.extend
, list.extend
返回None
,因此不能与reduce
一起使用。 除了建议使用lambda
函数之外,您还可以使用list.__add__
with reduce
:
>>> reduce(list.__add__, [[1],[2]], [])
[1, 2]
您可能想要使用itertools.chain
创建一个迭代器,它返回第一个iterable中的元素,直到它耗尽,然后进入下一个iterable,直到所有的iterables都用完为止。 用于将连续序列作为单个序列处理。 相当于:
def chain(*iterables):
# chain('ABC', 'DEF') --> A B C D E F
for it in iterables:
for element in it:
yield element
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.