[英]How do you add list containing another set of lists in python?
I have a set of lists which contain another set of lists.我有一组列表,其中包含另一组列表。 I just want to add them but I'm not able to since python doesn't allow me.我只想添加它们,但我无法添加,因为 python 不允许我添加。 I'm new to python programming and this thing is bugging me from 2 hours though it looks so simple.我是 python 编程的新手,虽然这件事看起来很简单,但它从 2 小时开始就困扰着我。 Here is the list:这是清单:
list = ['60.50', '120', '60', '185', '183.84', '134.50', '369.65', '112.50', '141.54', '141.60', '80', '125', '509.40', '99', '148', '86', '234.40', '135', '81', '97', '395', '193', '185', '261', '72', '157', '138', '90', '101', '72', '125', '116', '106', '118', '123', '128', '107', '81', '204.40', '136', '170.32', '136', '88.50', '114', '76', '125.72']
I have already tried a number of ways but still I'm not able to add these values.我已经尝试了多种方法,但仍然无法添加这些值。 Please help请帮忙
From the comments it seems you want to take a list of strings which are decimal numbers, and add them all together.从评论看来,您似乎想要获取一个十进制数字字符串列表,并将它们加在一起。
Rather than using floats for this, I would use Decimal
.而不是为此使用浮点数,我会使用Decimal
。 First convert all the items to decimals, then add them.首先将所有项目转换为小数,然后添加它们。
(Also don't call it list
) (也不要称之为list
)
from decimal import Decimal
l = [...]
print(sum(Decimal(i) for i in l))
If the list has multiple dimensions, you'll need to flatten the list first.如果列表有多个维度,您需要先展平列表。 We can make a function to sum numbers in generic multi-dimensional lists.我们可以创建一个函数来对通用多维列表中的数字求和。
from decimal import Decimal
def flatten(l):
for i in l:
if isinstance(i, str):
yield Decimal(i)
else:
yield from flatten(i)
l = [[...], ...]
print(sum(flatten(l))
确保首先以 numpy array ar pandas 数据帧的形式打印你的列表,然后简单地使用 sum() 函数......希望它有帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.