使用 sum() 连接元组

Concatenate tuples using sum()(使用 sum() 连接元组)
本文介绍了使用 sum() 连接元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

从这篇文章我了解到您可以使用 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() 连接元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

patching a class yields quot;AttributeError: Mock object has no attributequot; when accessing instance attributes(修补类会产生“AttributeError:Mock object has no attribute;访问实例属性时)
How to mock lt;ModelClassgt;.query.filter_by() in Flask-SqlAlchemy(如何在 Flask-SqlAlchemy 中模拟 lt;ModelClassgt;.query.filter_by())
FTPLIB error socket.gaierror: [Errno 8] nodename nor servname provided, or not known(FTPLIB 错误 socket.gaierror: [Errno 8] nodename nor servname provided, or not known)
Weird numpy.sum behavior when adding zeros(添加零时奇怪的 numpy.sum 行为)
Why does the #39;int#39; object is not callable error occur when using the sum() function?(为什么在使用 sum() 函数时会出现 int object is not callable 错误?)
How to sum in pandas by unique index in several columns?(如何通过几列中的唯一索引对 pandas 求和?)