Python检查列表中的任何元素是否是字典中的键

dev*_*onj 7 python dictionary list

什么是Pythonic方法来检查列表中的任何元素是否是字典中的键?

例如,我有一份水果清单:

fruits = ['apples', 'bananas', 'pears']
Run Code Online (Sandbox Code Playgroud)

并且想要检查我的词典中的任何水果是否是关键,例如:

fruit_dict1 = {'apples': 4, 'oranges': 3, 'dragonfruit': 4} returns True

fruit_dict2 = {'oranges': 3, 'dragonfruit': 9, 'pineapples': 4} returns False
Run Code Online (Sandbox Code Playgroud)

到目前为止,我有:

def fruit_checker(list, dict):
    for fruit in list:
        if fruit in dict:
            return True
    return False
Run Code Online (Sandbox Code Playgroud)

在字典中查找水果感觉很奇怪,但似乎"在"中只搜索字典键. "in"如何与不同类型一起工作?

Rah*_*K P 8

试试这个

In [1]: any([i in fruit_dict1 for i in fruits])
Out[1]: True
In [2]: any([i in fruit_dict2 for i in fruits])
Out[2]: False
Run Code Online (Sandbox Code Playgroud)

工作

In [11]: [i in fruit_dict2 for i in fruits]
Out[11]: [False, False, False]
Run Code Online (Sandbox Code Playgroud)

检查存在的每个元素.并返回一个布尔值列表,any如果True存在则返回.

In [13]: any([True,False,False])
Out[13]: True
Run Code Online (Sandbox Code Playgroud)


Joh*_*024 7

让我们定义你的变量:

>>> fruits = ['apples', 'bananas', 'pears']
>>> fruit_dict1 = {'apples': 4, 'oranges': 3, 'dragonfruit': 4}
>>> fruit_dict2 = {'oranges': 3, 'dragonfruit': 9, 'pineapples': 4}
Run Code Online (Sandbox Code Playgroud)

现在,让我们测试会员资格:

>>> bool(set(fruits).intersection(fruit_dict1))
True
>>> bool(set(fruits).intersection(fruit_dict2))
False
Run Code Online (Sandbox Code Playgroud)

这个怎么运作

set(fruits)是一套水果.我们想要查找此集与字典的键集之间是否有任何重叠.要找到重叠的内容,我们可以使用交集方法:

>>> set(fruits).intersection(fruit_dict1)
set(['apples'])
Run Code Online (Sandbox Code Playgroud)

要将此转换为True表示非空交集,或将False转换为空交集,我们使用bool:

>>> bool(set(fruits).intersection(fruit_dict1))
True
Run Code Online (Sandbox Code Playgroud)

微小的变化

如果我们颠倒顺序,原则相同:

>>> bool(set(fruit_dict1).intersection(fruits))
True
>>> bool(set(fruit_dict2).intersection(fruits))
False
Run Code Online (Sandbox Code Playgroud)