简体   繁体   English

Python:具有重复名称的字符串和不同整数的嵌套列表。 我怎样才能

[英]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.

相关问题 我想从整数列表中删除所有字符串。 为什么这不起作用? - I want to remove all strings from a list of integers. Why doesn't this work? Python。 如何对包含字符串和整数的列表求和? - Python. How can I sum a list with strings and integers? 如何将嵌套列表字符串转换为整数,然后在python 3中对其进行排序? - How to convert nested list strings to integers then sort them in python 3? 重复整数的Python列表 - Python list of repeated integers 如何从整数取回数据。 我的 model.predict() 不工作 - How can I get back data from integers. My model.predict() is not working python使用字符串和整数将嵌套列表大写 - python capitalize nested list with strings and integers python-TypeError:字符串索引必须为整数。 怎么修? - python-TypeError: string indices must be integers. How to fix? “输入无效。 应该是字符串、字符串列表/元组或整数列表/元组。” ValueError:输入无效 - “Input is not valid. Should be a string, a list/tuple of strings or a list/tuple of integers.” ValueError: Input is not valid 如何在Python中将字符串列表转换为整数? - How do I convert a list of strings to integers in Python? 如何让用户只输入 5 个整数/字符串 a 到列表中? - How can I have the user input only 5 integers/strings a into a list?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM