删除字典列表中的元素 [英] remove element in list in a dictionary

查看:318
本文介绍了删除字典列表中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个大字典中,类似于

In a big dictionary, similar to

d = {}                                                                                   
d['a']=[1,2,3,4]                                                                         
d['b']=[1,2,3,4,5,6]                                                                     
d['c']=[1,2]                                                                             
d['d']=[1,4]

如何快速删除列表?

有没有办法链接列表中的四个? / />

Is there a way to link the fours in the lists? As in, eliminating one eliminates the others.

推荐答案

迭代字典的值,并从每个列表中删除4: / p>

Iterate over the values of the dictionary and remove the 4 from every list:

for a in d.itervalues():
    try:
        a.remove(4)
    except ValueError:
        pass

这不是很有效率,因为从一个列表是一个O(n)操作。使用不同的数据类型(例如一组)以获得更好的性能。

This is not really efficient, since removing an element from a list is an O(n) operation. Use a different data type (e.g. a set) for better performance.

如果字典值是集合,您可以执行

If the dictionary values are sets, you can do

for a in d.itervalues():
    a.discard(4)

这篇关于删除字典列表中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆