在Python字典中修改列表元素

2024-05-07 23:45:06 发布

您现在位置:Python中文网/ 问答频道 /正文

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函数。你能给我解释一下你的代码吗?这样我就可以操作它以备将来使用了?谢谢


Tags: 方法lambda函数代码价格数字类别字母表
3条回答

您可以使用dict comprehension

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

然后查找匹配项:

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循环:

for k, v in inventory.iteritems():
    v[1] += 1

如果您使用的是python3,那么应该使用items而不是iteritems。使用dict comprehension {k:[m,p+1,n] for k,(m,p,n) in inventory.items()}的解决方案意味着您将用一个新的obejct替换整个dict(这在某些场景中是好的,但在其他场景中不是那么好)。你知道吗

相关问题 更多 >