gpt4 book ai didi

python - 修改Python字典中的列表元素

转载 作者:行者123 更新时间:2023-12-01 04:34:47 25 4
gpt4 key购买 nike

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)

关于python - 修改Python字典中的列表元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31914882/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com