I'm trying to convert a string list into a int
list then add the elements.
Example:
convert test_list = ["1", "2", "5", "6"]
to [1, 2, 5, 6]
then add them to get 14
.
I'm trying to convert a string list into a int
list then add the elements.
Example:
convert test_list = ["1", "2", "5", "6"]
to [1, 2, 5, 6]
then add them to get 14
.
You can use map
>>> test_list = ["1", "2", "5", "6"]
>>> map(int,test_list)
[1, 2, 5, 6]
>>> sum(map(int,test_list))
14
Other possible ways incude
sum([int(i) for i in test_list])
List Compsum(int(i) for i in test_list)
Generator ExpressionNote - map
is a better alternative to list comp as mentioned here
map may be microscopically faster in some cases (when you're NOT making a lambda for the purpose, but using the same function in map and a listcomp). List comprehensions may be faster in other cases and most (not all) pythonistas consider them more direct and clearer.
Using a list comprehension:
test_list = ["1", "2", "5", "6"]
new_list = [int(x) for x in test_list]
print sum(new_list)
The answers already posted are better practice however, a very easy to understand approach would be:
int_list = []
count = 0
for item in test_list:
int_list.append(int(item))
count += int(item)
print(count)
In my opinion it's the best solution:
test_list = ["1", "2", "5", "6"]
def sum_strings(X):
"""changes the type to int and adds elements"""
return reduce(lambda x, y: int(x) + int(y), X)
print sum_strings(test_list)
Out:
14