简体   繁体   中英

Sum space-separated integers as string in a list

I currently have this list: ['5 4 7', '4 3 1', '6 8 4'', '4 8 6'] Note that not all numbers are separated by commas.

I would like to be able to calculate the total for each section of the list. For example, the first calculation should be 5+4+7 to give me 16. I would just like to know how to convert this list to be able to do maths calculations with the numbers.

split your strings, map to integer and perform sum on the resulting inputs, in a list comprehension:

>>> [sum(map(int,x.split())) for x in ['5 4 7', '4 3 1', '6 8 4', '4 8 6']]
[16, 8, 18, 18]

(works for negative values as well :))

You can also use regex:

import re
s = ['5 4 7', '4 3 1', '6 8 4', '4 8 6']
new_s = [sum(map(int, re.findall('\d+', b))) for b in s]

Output:

[16, 8, 18, 18]

However, if every digit is a single character, then you can use isdigit() :

last_result = [sum(map(int, filter(lambda x:x.isdigit(), i))) for i in s]

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