栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用sum()连接元组

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用sum()连接元组

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



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/611830.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号