✓ @anvd,根据您的问题,您想要搜索字典d中的值是否存在于列表rating1和rating2中。
如果我理解有误或者下面提供的解决方案不能满足您的需求,请评论说明。
我建议您创建另一个字典d_lists,将列表名称映射到原始列表对象。
步骤:
✓ 从d中获取每个键(列表名称)。
✓ 在d_lists中查找此键的存在。
✓ 从d_lists中获取相应的列表对象。
✓ 在选定的列表对象中查找d指向的值的存在。
✓ 如果找到元素,则停止迭代并搜索d中下一个值的存在。
✓ 打印相关消息。
这是您修改后的代码(稍作修改)
下面是另一个很好的示例。
rating_1 = ['nlo', 'yes']
rating_2 = ['no', 'yes']
d_lists = {
"rating_1": rating_1,
"rating_2": rating_2,
}
d = {'rating_2': u'no', 'rating_1': u'no'}
for list_name in d:
if list_name in d_lists:
found = False
for item in d_lists[list_name]:
if item == d[list_name]:
found = True
break
if found:
print "'" + d[list_name] + "' exists in", d_lists[list_name];
else:
print "'" + d[list_name] + "' doesn't exist in", d_lists[list_name]
else:
print "Couldn't find", list_name
输出:
'no' exists in ['no', 'yes']
'no' doesn't exist in ['nlo', 'yes']
现在,看另一个例子。
另一个大例子:
rating_1 = ['no', 'yes', 'good', 'best']
rating_2 = ['no', 'yes', 'better', 'worst', 'bad']
fruits = ["apple", "mango", "pineapple"]
d_lists = {
"rating_1": rating_1,
"rating_2": rating_2,
"fruits": fruits,
}
d = {'rating_2': u'best', 'rating_1': u'good', 'fruits2': "blackberry"}
for list_name in d:
if list_name in d_lists:
print "Found list referred by key/name", list_name, "=", d_lists[list_name];
found = False
for item in d_lists[list_name]:
if d[list_name] == item:
found = True
break
if found:
print "'" + d[list_name] + "' exists in", d_lists[list_name], "\n";
else:
print "'" + d[list_name] + "' doesn't exist in", d_lists[list_name], "\n"
else:
print "Couldn't find list referred by key/name ", list_name, "\n"
输出:
Found list referred by key/name rating_2 = ['no', 'yes', 'better', 'worst', 'bad']
'best' doesn't exist in ['no', 'yes', 'better', 'worst', 'bad']
Couldn't find list referred by key/name fruits2
Found list referred by key/name rating_1 = ['no', 'yes', 'good', 'best']
'good' exists in ['no', 'yes', 'good', 'best']
d
是什么样子? - user3483203