user3321218
user3321218

Reputation: 25

adding list indexes in python

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

Answers (5)

Andrew Clark
Andrew Clark

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

m.wasowski
m.wasowski

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

Kamehameha
Kamehameha

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

wnnmaw
wnnmaw

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

dg99
dg99

Reputation: 5663

sum = 0.
for l in listOfLists:
    sum += float(l[-1])

Upvotes: 0

Related Questions