python - 检查相应列表中是否存在值

标签 python python-2.7 list dictionary

我正在尝试创建一个 for 循环,动态检查相应列表中是否存在某些值。我不确切地知道我是否可以转换列表中的字符串,或者是否有更好的方法来执行此操作。

rating_1 = ['no', 'yes']
rating_2 = ['no', 'yes']

for item in d:
    if d[item] not in item: # I don't want to use the item,
                            # only get name that will match the respective list above
        print "value not allowed"

d =  {'rating_2': u'no', 'rating_1': u'no'}

最佳答案

my_lists = {
'rating_1' = ['no', 'yes'],
'rating_2' = ['no', 'yes'],
}

d =  {'rating_2': u'no', 'rating_1': u'no'}

for item in d:
    if d[item] not in my_list[item]:
        print "value not allowed"

或者,如果你想使用变量,使用vars()提供当前命名空间的字典,您可以在其中使用变量名作为键。

rating_1 = ['no', 'yes']
rating_2 = ['no', 'yes']

d =  {'rating_2': u'no', 'rating_1': u'no'}

for item in d:
    if d[item] not in vars()[item]:
        print "value not allowed"

关于python - 检查相应列表中是否存在值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50684708/

相关文章:

python-2.7 - java.io.IOException : Broken pipe on increasing number of mappers/reducers, 很多

python - 在 python 中, 'foo == (8 or 9)' 或 'foo == 8 or foo == 9' 更正确?

python - 如何将两个列表合并到一个数组中,这样我就不必对其进行硬编码

python - Pandas 系列中的字符串过滤器

Python 3.5 Pyperclip 模块导入失败

python - 使用 Python 直接从 zip 文件中读取 xml 文件

r - 从列表创建数据框

python - 访问python字典时出错

python - 如何在一个容器中运行 Flask 和 celery?

arrays - 如何在golang中使用for循环将值存储在结构中