user3265068
user3265068

Reputation:

Sum float values at each index point in nested lists

I have a list of 3 strings:

["Apple", "Orange", "Pear"]

and I have a list of lists which each contain 3 float values:

[[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]]

and I need to sum the inner list elements at each index point in the nested lists, and output this in the format:

[[0.5, "Apple"], [0.7, "Orange"], [0.9, "Pear"]]

I'm learning as I go, but this is beyond what I know so far. Any advice as to how to achieve this would be great.

Upvotes: 2

Views: 346

Answers (1)

thefourtheye
thefourtheye

Reputation: 239623

fruits, values = ["Apple", "Orange", "Pear"], [[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]]
print zip(map(sum, zip(*values)), fruits)
# [(0.5, 'Apple'), (0.7, 'Orange'), (0.8999999999999999, 'Pear')]

In the above code,

zip(*values)

will get all the corresponding elements in the values list together. It will produce

[(0.1, 0.4), (0.2, 0.5), (0.3, 0.6)]

now, we can to add them, so we do

map(sum, zip(*values))

which finds the sum of all the corresponding elements in the values list. The result would be like this

[0.5, 0.7, 0.8999999999999999]

Now, all we have to do is to map it with the corresponding fruits so we simply zip it. That's it :-)

Since, you are using Python 3.x, where zip returns an iterator instead of a list, you need to get the list like this

list(zip(map(sum, zip(*values)), fruits))

If you want to do this without zip and map, you can use

result = []
for i in range(len(fruits)):
    total = 0
    for j in range(len(values)):
        total += values[j][i]
    result.append([total, fruits[i]])
print result

Upvotes: 6

Related Questions