【问题标题】:How to iterate through keys in a dict and match against key/val in another dict如何遍历字典中的键并匹配另一个字典中的键/值
【发布时间】:2021-02-10 17:41:47
【问题描述】:

我正在尝试构建一个程序,该程序将采用 [int,int] 或键/值对的嵌套列表,并与另一个 dict 的键/val 匹配,并将第二个中的值添加到在启动的 int 变量中0.

from collections import Counter

shoe_sizes = [2,3,4,5,6,8,7,6,5,18]
shoe_collection = Counter(shoe_sizes)
customer_wants = [[6,55],[6,45], [6,55], [4,40], [18,60], [10, 50]]

income = 0
for i in customer_wants:
    if i in shoe_collection:
        income += dict[customer_wants[i][1]]
    print(income)

shoe_collection 中的键是鞋码,值是可用的数量。 我在这里要做的是获取customer_wants 中的每个嵌套列表,并检查shoe_collection 中的第一个元素(鞋码)是否可用。如果是这样,我想在customer_wants 中添加该嵌套列表的第二个元素(价格)并将其添加到income。 使用两个字典而不是将customer_wants 作为嵌套列表会更容易吗?我尝试比较 list-dict 和 dict-dict 但得到的 TypeErrors 都不是可散列的。谢谢!

【问题讨论】:

    标签: python arrays dictionary


    【解决方案1】:

    用这个替换你的for循环:

    for size, price in customer_wants:
        if shoe_collection[size] > 0:
            shoe_collection[size] -= 1
            income += price
    

    这是根据文档的原理,Counter 对象返回 0 丢失键,根据文档:

    Counter 对象有一个字典接口,只是它们为丢失的项目返回零计数,而不是引发 KeyError

    所以不需要检查某个键是否存在,我们只需要检查该键是否为正值即可。如果是,则将价值减少1 并将价格添加到收入中。

    【讨论】:

      【解决方案2】:

      也许你可以这样说,

      shoe_sizes = [2,3,4,5,6,8,7,6,5,18]
      
      customer_wants = [{'size':6,'value':55},{'size':6,'value':45}, {'size':6,'value':55}, {'size':4,'value':40}, {'size':18,'value':60}, {'size':10, 'value':50}]
      income = 0
      for i in customer_wants:
          if i['size'] in shoe_sizes:
             income+=i['value']
      

      【讨论】:

      • 嘿,shajahan,shoe_sizes 中的每个值都代表该尺码的一只鞋。一旦 customer_wants[i]['size'] 与 shoe_sizes 中的值匹配,就需要从列表中删除该值。您的解决方案导致收入为 255 而不是 200,因为它不只考虑 shoe_sizes 中的两个 6,而包含“size”的三个字典:customer_wants 中的 6。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-15
      • 2014-05-15
      • 1970-01-01
      相关资源
      最近更新 更多