使用sum()连接元组

发布于 2021-01-29 15:19:18

这篇文章中,我了解到您可以使用以下方式连接元组:

>>> tuples = (('hello',), ('these', 'are'), ('my', 'tuples!'))
>>> sum(tuples, ())
('hello', 'these', 'are', 'my', 'tuples!')

看起来不错。但是为什么这样做呢?并且,这是最佳选择,还是从itertools该构造中更可取呢?

关注者
0
被浏览
44
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    加法运算符在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



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看