Python 3:如何比较两个元组并找到相似的值?
Python 3: How to compare two tuples and find similar values?
我有两本词典:(1)Inventory and (2)Items
在这些字典下是使用用户输入添加的元组。
dict_inventory = {('fruits', ['apple','mango'])
dict_items = {('apple', [3, 5])
('mango', [4, 6])}
如何比较两者并匹配相似的值 apple
和 mango
我的代码没有打印任何东西:
for itemA in dict_inventory.values():
for itemB in dict_items.keys():
if itemA == itemB:
print("Match!")
您的原始 for-loop
是在迭代值时从清单字典中获取值作为 list
而不是 string
。由于它返回了一个列表,因此您还需要遍历这些值。这应该让你 运行:
inventory = {
"fruits": ["apples", "mangos",]
}
items = {
"apples": [3, 5],
"mangos": [4, 6],
}
for value in inventory.values():
for item_a in value:
if item_a in items.keys():
print("Match!")
不过,您可以合并这两个词典。
inventory = {
"fruits": {
"apples": [3, 5],
"mangos": [4, 6],
}
}
我有两本词典:(1)Inventory and (2)Items
在这些字典下是使用用户输入添加的元组。
dict_inventory = {('fruits', ['apple','mango'])
dict_items = {('apple', [3, 5])
('mango', [4, 6])}
如何比较两者并匹配相似的值 apple
和 mango
我的代码没有打印任何东西:
for itemA in dict_inventory.values():
for itemB in dict_items.keys():
if itemA == itemB:
print("Match!")
您的原始 for-loop
是在迭代值时从清单字典中获取值作为 list
而不是 string
。由于它返回了一个列表,因此您还需要遍历这些值。这应该让你 运行:
inventory = {
"fruits": ["apples", "mangos",]
}
items = {
"apples": [3, 5],
"mangos": [4, 6],
}
for value in inventory.values():
for item_a in value:
if item_a in items.keys():
print("Match!")
不过,您可以合并这两个词典。
inventory = {
"fruits": {
"apples": [3, 5],
"mangos": [4, 6],
}
}