✓ @anvd,我从您的问题中了解到,您想在列表 rating1 中搜索字典 d 的值是否存在& 评级2。
如果我错了或者我在下面提供的解决方案不能满足您的需求,请发表评论。
我建议您再创建 1 个字典 d_lists,将列表名称映射到原始列表对象。
步骤:
✓ 从 d 中获取每个键(列表名称)。
✓ 在 d_lists 中查找此键的存在。
✓ 从 d_lists 中获取对应的列表对象。
✓ 在选取的列表对象中找到 d 中键指向的值的存在。
✓ 如果找到元素,则停止迭代并搜索 d 中是否存在下一个值。
✓ 打印相关消息。
这是您修改后的代码(稍作修改)
我在下面的代码示例之后展示了另一个很好的示例。
rating_1 = ['nlo', 'yes']
rating_2 = ['no', 'yes']
# Creating a dictionary that maps list names to themselves (original list object)
d_lists = {
"rating_1": rating_1,
"rating_2": rating_2,
}
# Creating a dictionary that maps list to the item to be searched
# We just want to check whether 'rating_1' & 'rating_2' contains 'no' or not
d = {'rating_2': u'no', 'rating_1': u'no'}
# Search operation using loop
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"]
# Creating a dictionary that maps list names to themselves (original list object)
d_lists = {
"rating_1": rating_1,
"rating_2": rating_2,
"fruits": fruits,
}
# Creating a dictionary that maps list to the item to be searched
# We just want to check whether 'rating_1' & 'rating_2' contains 'no' or not
d = {'rating_2': u'best', 'rating_1': u'good', 'fruits2': "blackberry"}
# Search operation using loop
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']