I have a list that looks like this:
['9,7,4', '10,5,6,5,5', '10,8,5,3,0', '8,4,2']
How can i convert the numbers to ints and add the individual string values together?
So the desired out put would be
['20','31','26','14']
Use map
to convert the splitted (using ,
as the delimiter) string values into int
followed by a list comprehension to get the sum
input_list = ['9,7,4', '10,5,6,5,5', '10,8,5,3,0', '8,4,2']
output = [str(sum(map(int, x.split(',')))) for x in input_list]
print (output)
Output
['20', '31', '26', '14']
I edited after seeing your desired output as strings
[sum(map(int, group.split(','))) for group in l]
Someone mentioned eval
, so I think you should take this a step further with a safe-eval alternative:
>>> import ast
>>> [ast.literal_eval(v.replace(',', '+')) for v in lst]
>>> [20, 31, 26, 14]
One thing I like about this answer is that it is purely a non-functional approach (no map
inside a list comprehension, which is fine but I don't really believe in mixing paradigms).
Obviously this will only work if you have numbers separated by a single comma, without any leading or trailing characters and invalid arithmetic expressions.
I leave the conversion to string as an exercise.
If all strings are in this format you can try to use eval
function - this will convert numbers into tuples from which you can count sum.
>>> l = ['9,7,4', '10,5,6,5,5', '10,8,5,3,0', '8,4,2']
>>> sums = [sum(numbers) for numbers in map(eval, l)]
>>> sums
[20, 31, 26, 14]
If you want output list to contain strings these values can be easily mapped:
[str(value) for value in sums]
# or
map(str, sums)
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.