如何遍历字典中的键,并在另一个字典中匹配key/val



我正在尝试构建一个程序,该程序将采用[int,int]或键/值对的嵌套列表,并与另一个字典的key/val匹配,并将第二个值添加到初始值为0的int变量。

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都是不可哈希的。谢谢!

用这个替换你的for循环:

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

它的工作原理是,Counter对象对于丢失的键返回0,按照文档:

计数器对象有一个字典接口,除了它们对缺少的项返回零计数而不是引发KeyError

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

也许你可以这么说,

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']

最新更新