![](/img/trans.png)
[英]Modifying the first element of each tuple in a list of list by getting a dictionary value
[英]modifying list element in Python dictionary
inventory = {'A':['Toy',3, 1000], 'B':['Toy',8, 1100],
'C':['Cloth',15, 1200], 'D':['Cloth',9, 1300],
'E':['Toy',11, 1400], 'F':['Cloth', 18, 1500], 'G':['Appliance', 300, 50]}
字母是商品名称,[]括号中的第一个字段是商品的类别,[]括号中的第二个字段是价格,第三个是已售出的数字。
我希望价格增加1,所以结果看起来像。
inventory = {'A':['Toy',4, 1000], 'B':['Toy',9, 1100],
'C':['Cloth',16, 1200], 'D':['Cloth',10, 1300],
'E':['Toy',12, 1400], 'F':['Cloth', 19, 1500], 'G':['Appliance', 301, 50]}
然后,找到一个价格为$ 19的商品的最佳方法是循环浏览。
我不擅长lambda函数。 您能否给我一些关于您的代码的解释,以便我可以将来使用? 谢谢
尝试这个:
for k, v in inventory.iteritems():
v[1] += 1
然后找到匹配项:
price_match = {k:v for (k,v) in inventory.iteritems() if v[1] == 19}
查找匹配项的lambda:
find_price = lambda x: {k:v for (k,v) in inventory.iteritems() if v[1] == x}
price_match = find_price(19)
您可以使用dict理解 :
>>> new={k:[m,p+1,n] for k,(m,p,n) in inventory.items()}
{'G': ['Appliance', 301, 50], 'E': ['Toy', 12, 1400], 'D': ['Cloth', 10, 1300], 'B': ['Toy', 9, 1100], 'A': ['Toy', 4, 1000], 'C': ['Cloth', 16, 1200], 'F': ['Cloth', 19, 1500]}
>>>
对于寻找特殊物品:
>>> {k:[m,p,n] for k,(m,p,n) in new.items() if p==19}
{'F': ['Cloth', 19, 1500]}
如果您不想“就地”修改数据,则可以遍历字典:
for k, v in inventory.iteritems():
v[1] += 1
如果您使用的是python3, iteritems
使用items
而不是iteritems
。 对{k:[m,p+1,n] for k,(m,p,n) in inventory.items()}
使用dict理解{k:[m,p+1,n] for k,(m,p,n) in inventory.items()}
的解决方案意味着您将用新对象替换整个dict
(即在某些情况下很好,但在其他情况下不好)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.