简体   繁体   中英

How to sum certain numbers in a python list?

I have a list that contains [date,data1,data2,data3...]. Now I need to sum all the data but not the date. How could I do that? I hope I could get a new list that looks like [date,data1+data2+data3...]

You can use list slicing to get all of the original list except the first element. Then you can pass the resulting slice to sum() .

>>> original = ['date',11,222,3]
>>> summed = [original[0], sum(original[1:])]
>>> print(summed)
['date', 236]

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM