使用sum()连接元组
从这篇文章中,我了解到您可以使用以下方式连接元组:
>>> tuples = (('hello',), ('these', 'are'), ('my', 'tuples!'))
>>> sum(tuples, ())
('hello', 'these', 'are', 'my', 'tuples!')
看起来不错。但是为什么这样做呢?并且,这是最佳选择,还是从itertools
该构造中更可取呢?
-
加法运算符在python中连接元组:
('a', 'b')+('c', 'd') Out[34]: ('a', 'b', 'c', 'd')
来自以下文档的字符串
sum
:返回“起始”值(默认值:0)和可迭代数字的总和
这意味着
sum
不是从iterable的第一个元素开始,而是从通过start=
参数传递的初始值开始。默认情况下
sum
用于数字,因此默认起始值为0
。因此,总结一个可迭代的元组需要从一个空的元组开始。()
是一个空元组:type(()) Out[36]: tuple
因此工作级联。
根据性能,这是一个比较:
%timeit sum(tuples, ()) The slowest run took 9.40 times longer than the fastest. This could mean that an intermediate result is being cached. 1000000 loops, best of 3: 285 ns per loop %timeit tuple(it.chain.from_iterable(tuples)) The slowest run took 5.00 times longer than the fastest. This could mean that an intermediate result is being cached. 1000000 loops, best of 3: 625 ns per loop
现在,t2的大小为10000:
%timeit sum(t2, ()) 10 loops, best of 3: 188 ms per loop %timeit tuple(it.chain.from_iterable(t2)) 1000 loops, best of 3: 526 µs per loop
因此,如果您的元组列表很小,您就不会打扰。如果是中等大小或更大,则应使用
itertools
。