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

标签 python list dictionary

<分区>

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

例如,我有一个水果列表:

fruits = ['apples', 'bananas', 'pears']

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

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

fruit_dict2 = {'oranges': 3, 'dragonfruit': 9, 'pineapples': 4} returns False

到目前为止我有:

def fruit_checker(list, dict):
    for fruit in list:
        if fruit in dict:
            return True
    return False

只在字典“中”查找水果感觉很奇怪,但似乎“在”中只搜索字典键。 “in”究竟如何处理不同的类型?

最佳答案

试试这个

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

工作

In [11]: [i in fruit_dict2 for i in fruits]
Out[11]: [False, False, False]

检查每个元素是否存在。并返回一个 bool 值列表,如果存在任何 Trueany 将返回。

In [13]: any([True,False,False])
Out[13]: True

关于Python检查列表中的任何元素是否是字典中的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38238861/

相关文章:

python - 如何以节省内存的方式重命名 pandas 数据框(无需创建副本)?

Java Selenium 通过 li 迭代列表

python - 在Python中设置嵌套字典: Why class method behaves differently from an standalone function?

python - 从 json 文件中删除所有 xmlns 标记

Python Pyramid PServe 拒绝服务

python - 使用其他函数中的变量而不使用 "running"函数 (Python Qt)

python - 使用 python-docx-template (docxtpl) 时循环遍历列表(或字典)

python - 在迭代列表中的元素时,如何在 python 中创建对象?

jquery - <li> 的页面转换不起作用

python - 将列表转换为嵌套字典