【问题标题】:Python 3: How to compare two tuples and find similar values?Python 3:如何比较两个元组并找到相似的值?
【发布时间】:2019-03-11 06:07:02
【问题描述】:

我有两个字典:(1)Inventory and (2)Items 在这些字典下是使用用户输入添加的元组。

 dict_inventory = {('fruits', ['apple','mango'])

 dict_items = {('apple', [3, 5])
    ('mango', [4, 6])}

如何比较两者并匹配applemango 的相似值

我的代码没有打印任何东西:

for itemA in dict_inventory.values():
    for itemB in dict_items.keys():
        if itemA == itemB:
            print("Match!")

【问题讨论】:

  • 请准确定义您的字典,例如print(dict_inventory)。如果不了解这些是如何定义的,我们很难提供帮助。
  • 你需要使用两个字典吗?您可以将它们组合成一个嵌套字典。
  • @jpp 我一周前开始使用 Python。我真的不确定你的意思,但这些词典也是使用用户输入添加的。但我会编辑帖子并添加我认为您可能需要的代码。
  • @Tanmayjain 是的。
  • 你能编辑你的问题并放入样本(1)库存和(2)项目字典

标签: python python-3.x dictionary tuples


【解决方案1】:

当您迭代这些值时,您原来的 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],
    }
}

【讨论】:

  • 这回答了我的问题!我只是想知道这是如何正确的,而我的却不是?
  • 我看到你的解释晚了。
  • @Geni-sama 你真的有这个写在你的代码dict_inventory = {('fruits', ['apple','mango'])is <class 'tuple'>} 吗?如果是这样,它的错误 python 应该给你 SyntaxError: invalid syntax
  • @Geni-sama 如果这回答了你的问题,请考虑接受它。
  • @Tanmayjain 不。这只是输出。这是我的完整代码:pastebin.com/fkkxiwCJ 很乱所以我没有在这里展示以避免混淆
猜你喜欢
  • 1970-01-01
  • 2021-12-07
  • 1970-01-01
  • 1970-01-01
  • 2015-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多