使用sum()连接元组 [英] Concatenate tuples using sum()

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

问题描述

来自这篇文章我了解到您可以使用以下方法连接元组:

From this post I learned that you can concatenate tuples with:

>>> 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 optimum, 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并非以iterable的第一个元素开头,而是以通过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()连接元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆