+-
python-检查相应列表中是否存在值
我试图创建一个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-检查相应列表中是否存在值 - 乐贴网