热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

从列表中删除dict的子集-Removingasubsetofadictfromwithinalist

Thisisreallyonlyeasytoexplainwithanexample,sotoremovetheintersectionofalistfromwi

This is really only easy to explain with an example, so to remove the intersection of a list from within a dict I usually do something like this:

这只是一个例子很容易解释,所以要从dict中删除列表的交集我通常会这样做:

a = {1:'', 2:'', 3:'', 4:''}
exclusion = [3, 4, 5]

# have to build up a new list or the iteration breaks
toRemove = []
for var in a.iterkeys():
    if var in exclusion:
        toRemove.append(var)

for var in toRemove:
    del a[var]

This might seem like an unusual example, but it's surprising the number of times I've had to do something like this. Doing this with sets would be much nicer, but I clearly want to retain the 'values' for the dict.

这似乎是一个不寻常的例子,但令人惊讶的是我必须做这样的事情的次数。使用集合执行此操作会更好,但我显然希望保留dict的“值”。

This method is annoying because it requires two loops and an extra array. Is there a cleaner and more efficient way of doing this.

这种方法很烦人,因为它需要两个循环和一个额外的数组。是否有更清洁,更有效的方法。

4 个解决方案

#1


12  

Consider dict.pop:

for key in exclusion:
     a.pop(key, None)

The None keeps pop from raising an exception when key isn't a key.

当密钥不是密钥时,None保持pop不会引发异常。

#2


3  

a = dict((key,value) for (key,value) in a.iteritems() if key not in exclusion)

#3


2  

Why not just use the keys method, instead of iterkeys? That way you can do it in one loop because it returns a list, not an iterator.

为什么不使用keys方法而不是iterkeys呢?这样你就可以在一个循环中完成它,因为它返回一个列表而不是一个迭代器。

#4


1  

You could change your exclusion list to a set, then just use intersection to get the overlap.

您可以将排除列表更改为集合,然后只使用交集来获取重叠。

exclusion = set([3, 4, 5])

for key in exclusion.intersection(a):
    del a[key]

推荐阅读
author-avatar
kakeru0o0
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有