0

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']
4
  • loop through the list, split the strings by commas, convert to ints (int(string)) and sum the resultant list. Commented Aug 4, 2018 at 22:05
  • You should do this, if I understood: 1) iterate through the strings, 2) split the strings on commas 3) convert split strings to integers, 4) merge the result into one list. Which part do you have a question about? Commented Aug 4, 2018 at 22:06
  • So, the true question is: how to find the sum of '9,7,4'? (If you can do that, you can do the rest.) split the string, convert each fragment to an int, apply sum, convert back to a string. Commented Aug 4, 2018 at 22:06
  • Hey, i updated my question. Sorry for the confusion. Commented Aug 4, 2018 at 22:08

4 Answers 4

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

using map inside a list comprehension is quite expensive. I guess you ould use vectorized functions after splitting.
[str(sum(np.array(i.split(","),dtype="i"))) for i in input_list]
2
[sum(map(int, group.split(','))) for group in l]

Comments

1

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.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.