問題描述
從這篇文章我了解到您可以使用 sum()
連接元組:
From this post I learned that you can concatenate tuples with sum()
:
>>> tuples = (('hello',), ('these', 'are'), ('my', 'tuples!'))
>>> sum(tuples, ())
('hello', 'these', 'are', 'my', 'tuples!')
這看起來很不錯.但為什么這行得通?而且,這是最優的,還是 itertools
中的某些東西比這個結構更可取?
Which looks pretty nice. But why does this work? And, is this optimal, or is there something from itertools
that would be preferable to this construct?
推薦答案
python中的加法運算符連接元組:
the addition operator concatenates tuples in python:
('a', 'b')+('c', 'd')
Out[34]: ('a', 'b', 'c', 'd')
來自sum
的文檔字符串:
返回一個開始"值(默認值:0)加上一個可迭代的數字
Return the sum of a 'start' value (default: 0) plus an iterable of numbers
這意味著 sum
不是從可迭代的第一個元素開始,而是從通過 start=
參數傳遞的初始值開始.
It means sum
doesn't start with the first element of your iterable, but rather with an initial value that is passed through start=
argument.
默認情況下 sum
與數字一起使用,因此默認起始值??為 0
.因此,對一個可迭代的元組求和需要從一個空元組開始.()
是一個空元組:
By default sum
is used with numeric thus the default start value is 0
. So summing an iterable of tuples requires to start with an empty tuple. ()
is an empty tuple:
type(())
Out[36]: tuple
因此工作串聯.
根據性能,這里是一個比較:
As per performance, here is a comparison:
%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:
Now with t2 of a size 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
.
So if your list of tuples is small, you don't bother. If it's medium size or larger, you should use itertools
.
這篇關于使用 sum() 連接元組的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!