【发布时间】:2015-04-03 07:45:32
【问题描述】:
对于我的程序,我希望清楚地检查列表中的任何元素是否是字典中的键。到目前为止,我只能想到循环遍历列表并检查。
但是,有什么方法可以简化这个过程?有什么方法可以使用集合吗?通过集合,可以检查两个列表是否有共同的元素。
【问题讨论】:
标签: python list dictionary set
对于我的程序,我希望清楚地检查列表中的任何元素是否是字典中的键。到目前为止,我只能想到循环遍历列表并检查。
但是,有什么方法可以简化这个过程?有什么方法可以使用集合吗?通过集合,可以检查两个列表是否有共同的元素。
【问题讨论】:
标签: python list dictionary set
使用内置的any 函数应该很容易:
any(item in dct for item in lst)
这是快速、高效且(恕我直言)非常易读的。有什么更好的? :-)
当然,这并不能告诉您 哪些 键在字典中。如果你需要,那么你最好的办法是使用字典视图对象:
# python2.7
dct.viewkeys() & lst # Returns a set of the overlap
# python3.x
dct.keys() & lst # Same as above, but for py3.x
【讨论】:
您可以使用dict.keys 测试字典键和列表项之间的交集:
if the_dict.keys() & the_list:
# the_dict has one or more keys found in the_list
演示:
>>> the_dict = {'a':1, 'b':2, 'c':3}
>>> the_list = ['x', 'b', 'y']
>>> if the_dict.keys() & the_list:
... print('found key in the_list')
...
found key in the_list
>>>
请注意,在 Python 2.x 中,该方法称为 dict.viewkeys。
【讨论】:
set;在现代 Python 中,您可以使用 the_dict.keys() & the_list,或者在 2 中使用 the_dict.viewkeys() & the_list。
就效率而言,您不能比遍历列表更高效。我还认为遍历列表已经是一个简单的过程。
【讨论】: