在你说的cmets里
我是 python 的初学者,我想慢慢来,理解得很好
所以我将重点放在解释步骤上,而不是直接给你解决方案。
检查 one 字典是否包含特定键的最简单方法是使用in:
>>> d = {'a': 10, 'b': 20}
>>> 'a' in d
True
>>> 'c' in d
False
同样,您可以使用not in 来检查它是否不是字典中的键:
>>> 'c' not in d
True
>>> 'b' not in d
False
由于您正在处理一个字典列表,因此您需要对其进行迭代。使用 Python,您可以使用 for 遍历每个元素:
>>> list_of_dicts = [{'a': 10, 'b': 20}, {'b': 10, 'c': 20}]
>>> for subdict in list_of_dicts:
... print(subdict)
...
{'a': 10, 'b': 20}
{'b': 10, 'c': 20}
因此,您基本上只需将for 循环与检查键是否为in 子字典结合起来。但是,修改当前迭代的内容并不是一个好主意,因此您可以创建一个新列表来存储要保留的字典:
>>> keep_these = []
>>> for subdict in list_of_dicts:
... if 'a' not in subdict:
... keep_these.append(subdict)
...
>>> keep_these
[{'b': 10, 'c': 20}]
在 Python 中有一种更简单的方法:列表推导式。 Moinuddin Quadri 已经介绍过,但只是重复一遍:
>>> [subdict for subdict in list_of_dicts if 'a' not in subdict]
[{'b': 10, 'c': 20}]
这本质上与我上面使用的for 循环完全相同,但它更短、更快。