jack west
jack west

Reputation: 641

Normalise numbers in nested list

I'm trying to normilise the second item in the below list to 1. I can do this if the list only has numbers in a single list as follows

rank = [['a', 234],['b',435],['c',567]]

ranking = [float(i)/sum(rank) for i in rank]

However when the list has a second item and is nested this fails with

ranking = [float(i[1])/sum(rank) for i[1] in rank]

Upvotes: 2

Views: 166

Answers (2)

Jean-François Fabre
Jean-François Fabre

Reputation: 140256

you have to consider the second item of the sublist when performing computations

rank = [['a', 234],['b',435],['c',567]]

ranking = [[i[0],i[1]/sum(r[1] for r in rank)] for i in rank]

print(ranking)

result

[['a', 0.18932038834951456], ['b', 0.35194174757281554], ['c', 0.4587378640776699]]

note that this is one liner but not very efficient since sum(r[1] for r in rank) is recomputed every time. You could compute it first, then use it in your list comprehension.

Upvotes: 2

Dorijan Cirkveni
Dorijan Cirkveni

Reputation: 164

The function call sum(rank)will attempt to sum up all members of the rank list. When they are not numbers (e.g. lists), this will fail.

You need to calculate the normalizer by making a sum of the list elements, e.g. like this:

normalizer=sum([e[1] for e in rank])

(also, calculating the normalizer for every list member is bad coding practice).

Here's the fixed code:

rank = [['a', 234],['b',435],['c',567]]
normalizer=sum([e[1] for e in rank])
ranking=[float(e[1])/normalizer for e in rank]

Upvotes: 3

Related Questions