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

从单一列表构建字典的最Pythonic方法

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

从单一列表构建字典的最Pythonic方法

除了

dict.fromkeys
您还可以使用
dict-comprehension
,但是
fromkeys()
比dict理解要快:

In [27]: lis = ['a', 'b', 'c', 'd']In [28]: dic = {x: 0 for x in lis}In [29]: dicOut[29]: {'a': 0, 'b': 0, 'c': 0, 'd': 0}

对于2.6及更早版本:

In [30]: dic = dict((x, 0) for x in lis)In [31]: dicOut[31]: {'a': 0, 'b': 0, 'c': 0, 'd': 0}

timeit
比较:

In [38]: %timeit dict.fromkeys(xrange(10000), 0)         # winner1000 loops, best of 3: 1.4 ms per loopIn [39]: %timeit {x: 0 for x in xrange(10000)}100 loops, best of 3: 2.08 ms per loopIn [40]: %timeit dict((x, 0) for x in xrange(10000))100 loops, best of 3: 4.63 ms per loop

正如@Eumiro和@mgilson在评论中所提到的,需要注意的是

fromkeys()
dict-comprehensions
如果使用的值是可变对象,则可能返回不同的对象:

In [42]: dic = dict.fromkeys(lis, [])In [43]: [id(x) for x in dic.values()]Out[43]: [165420716, 165420716, 165420716, 165420716] # all point to a same objectIn [44]: dic = {x: [] for x in lis}In [45]: [id(x) for x in dic.values()]Out[45]: [165420780, 165420940, 163062700, 163948812]  # unique objects


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

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

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