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. I'm new to python programming and this thing is bugging me from 2 hours though it looks so simple. 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
. First convert all the items to decimals, then add them.
(Also don't call it 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() 函数......希望它有帮助
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.