简体   繁体   中英

How to sum all invidual integers (parts of integers) within a list of integers?

In other words, I have a list like this [10, 11, 22, 6, 4, 9] and I want it to add up all the individual integers. So, 1 + 0 + 1 + 1 + 2 + 2 + 6 + 4 + 9 .

I have tried using the sum function and other various suggestions online and I'm still lost. What could I do to break up the integers so I can sum the individual parts? Slicing? Indexing? Happy to answer any questions!!!

you can iterate through each integer as a string and get the sum of each part of it.

>>> lst = [10, 11, 22, 6, 4, 9]
>>> sum([int(i) for x in lst for i in str(x)])
26

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