[英]Python: Nested list with repeated name of strings and different integers. How can I
If I have the following nested list:如果我有以下嵌套列表:
products.store = [['Shampoo', 35], ['Soap', 100], ['Soap', 150],['Towels', 45], ['Shampoo', 55]] products.store = [['洗发水', 35], ['肥皂', 100], ['肥皂', 150],['毛巾', 45], ['洗发水', 55]]
How can I write a program where each product is associated to total amount of products?我如何编写一个程序,其中每个产品都与产品总量相关联?
So that the output will still be in a nested list, like this: [['Shampoo', 90], ['Soap', 250],['Towels', 45]]这样 output 仍将位于嵌套列表中,如下所示: [['Shampoo', 90], ['Soap', 250],['Towels', 45]]
I have tried multiple solutions, but have failed to make the integers associated to a singular product.我尝试了多种解决方案,但未能将整数与单个产品相关联。
Sorry if this is an easy question, it is my first term in university with coding.对不起,如果这是一个简单的问题,这是我在大学的第一个学期编码。 (Not for homework, a test or something like that). (不适用于家庭作业、测试或类似的东西)。 I would just love to learn how to improve my codes and better understand:) Thank you for your help!我很想学习如何改进我的代码并更好地理解:) 谢谢你的帮助!
Try:尝试:
products = [
["Shampoo", 35],
["Soap", 100],
["Soap", 150],
["Towels", 45],
["Shampoo", 55],
]
out = {}
for a, b in products:
out[a] = out.get(a, 0) + b
out = list(map(list, out.items()))
print(out)
Prints:印刷:
[["Shampoo", 90], ["Soap", 250], ["Towels", 45]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.