0

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.

5 Answers 5

4
>>> data = [['1', '1', '1', '1', '1', '.12'], ['1', '1', '1', '1', '1', '.13']]
>>> sum(float(x[-1]) for x in data)
0.25
Sign up to request clarification or add additional context in comments.

1 Comment

Works perfectly! One last question, is there a way to round the resulting number to 2 decimal places?
0
sum = 0.
for l in listOfLists:
    sum += float(l[-1])

Comments

0

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

Comments

0

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

Comments

0
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)

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.