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

从列表中删除字典

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

从列表中删除字典

thelist[:] = [d for d in thelist if d.get('id') != 2]

编辑
:由于对此代码的性能提出了一些疑问(一些基于对Python的性能特征的误解,一些基于超出给定规范的假设,即列表中仅存在一个dict,其key的值为2)
id”),我希望在此方面给您保证。

在旧的Linux机器上,测量以下代码:

$ python -mtimeit -s"lod=[{'id':i, 'name':'nam%s'%i} for i in range(99)]; import random" "thelist=list(lod); random.shuffle(thelist); thelist[:] = [d for d in thelist if d.get('id') != 2]"10000 loops, best of 3: 82.3 usec per loop

其中约57微秒用于random.shuffle(需要确保要删除的元素始终不在同一位置;-),而初始副本则为0.65微秒(最担心Python列表的浅表副本对性能的影响最大)显然是在吃午饭了;-),需要避免更改循环中的原始列表(因此循环的每一行确实都有一些要删除的内容;-)。

当知道只有一个要删除的项目时,可以更快速地找到并删除它:

$ python -mtimeit -s"lod=[{'id':i, 'name':'nam%s'%i} for i in range(99)]; import random" "thelist=list(lod); random.shuffle(thelist); where=(i for i,d in enumerate(thelist) if d.get('id')==2).next(); del thelist[where]"10000 loops, best of 3: 72.8 usec per loop

(当然,如果您使用的是python
2.6或更高版本,请使用

next
内置函数,而不要使用该
.next
方法)-但是,如果满足删除条件的命令数量不完全相同,则此代码将崩溃。概括地说,我们有:

$ python -mtimeit -s"lod=[{'id':i, 'name':'nam%s'%i} for i in range(33)]*3; import random" "thelist=list(lod); where=[i for i,d in enumerate(thelist) if d.get('id')==2]; where.reverse()" "for i in where: del thelist[i]"10000 loops, best of 3: 23.7 usec per loop

众所周知,在这里可以删除混洗,因为已经删除了三个等距的字典。而listcomp保持不变:

$ python -mtimeit -s"lod=[{'id':i, 'name':'nam%s'%i} for i in range(33)]*3; import random" "thelist=list(lod); thelist[:] = [d for d in thelist if d.get('id') != 2]"10000 loops, best of 3: 23.8 usec per loop

完全并驾齐驱,甚至只需删除99个元素中的3个。有了更长的列表和更多的重复,这当然具有更多的优势:

$ python -mtimeit -s"lod=[{'id':i, 'name':'nam%s'%i} for i in range(33)]*133; import random" "thelist=list(lod); where=[i for i,d in enumerate(thelist) if d.get('id')==2]; where.reverse()" "for i in where: del thelist[i]"1000 loops, best of 3: 1.11 msec per loop$ python -mtimeit -s"lod=[{'id':i, 'name':'nam%s'%i} for i in range(33)]*133; import random" "thelist=list(lod); thelist[:] = [d for d in thelist if d.get('id') != 2]"1000 loops, best of 3: 998 usec per loop

总而言之,显然不值得部署制作和反转索引列表以删除的精妙之处,而不是完全简单明了的列表理解,在一个小情况下可能会增加100纳秒,而在较大的情况下会损失113微秒。
;-)。避免或批评简单,直接,完美的性能适当的解决方案(例如对此类“从列表中删除某些物品”问题的一般理解),是Knuth和Hoare的著名论点,即“过早的优化是编程中所有邪恶的根源!-)



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

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

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