Reputation: 25
Say I have this list:
[['1', '1', '1', '1', '1', '.12'], ['1', '1', '1', '1', '1', '.13']]
And I want to add together the final element of each array (.12 and .13), how do I convert these strings to a real number, and add them together? Also assuming that each array in the list could be of different length.
Upvotes: 0
Views: 76
Reputation: 208475
>>> data = [['1', '1', '1', '1', '1', '.12'], ['1', '1', '1', '1', '1', '.13']]
>>> sum(float(x[-1]) for x in data)
0.25
Upvotes: 4
Reputation: 6387
as_string = [['1', '1', '1', '1', '1', '.12'], ['1', '1', '1', '1', '1', '.13']]
as_numbers = [map(float, arr) for arr in as_string]
result = sum(arr[-1] for arr in as_numbers)
or just:
result = sum(float(arr[-1]) for arr in as_string)
Upvotes: 0
Reputation: 5473
This works -
>>> li = [['1', '1', '1', '1', '1', '.12'], ['1', '1', '1', '1', '1', '.13']]
>>> reduce(lambda x,y:float(x[-1])+float(y[-1]), li)
0.25
Upvotes: 0
Reputation: 5514
It should be as simple as:
sum(map(float,(lst1[-1],lst2[-1])))
Sample output:
>>> lst1 = ["1", ".1"]
>>> lst2 = ["1", ".2"]
>>> sum(map(float,(lst1[-1],lst2[-1])))
0.30000000000000004
Upvotes: 0