我正在尝试构建一个程序,该程序将使用[int,int]或键/值对的嵌套列表,并与另一个dict的键/ 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
并为收入增加价格。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句