-1

If I have a list of lists, for example,

[[1, 2, 3], [4, 5, 6], [7, 8, 9], [0,0,0]]

How do I output a list of lists, such that each element is assigned as a fraction of the sum of the sub-list.

In this example, the output should be:

[[1/6, 2/6, 3/6], [4/15, 5/15, 6/15], [7/24, 8/24, 9/24], [0,0,0]]

and should also check for division by zero, in which case, the entries are just zero.

Mat.S
  • 1,814
  • 7
  • 24
  • 36

4 Answers4

2

you can use sum of the sublist:

l =  [[1,2,3],[4,5,6],[7,8,9]]
res = [map(lambda x: float(x)/sum(sl), sl) for sl in l]

Results with

[[0.16666666666666666, 0.3333333333333333, 0.5], 
 [0.26666666666666666, 0.3333333333333333, 0.4], 
 [0.2916666666666667, 0.3333333333333333, 0.375]]

PS,
For [map(...) does not return a list, but a map object]1. To get a list:

res = [list(map(lambda x: float(x)/sum(sl), sl)) for sl in l]

PPS,
To avoid division by zero, you can replace the denominator with a conditional expression: sum(sl) if sum(sl) else 1:

[list(map(lambda x: float(x)/(sum(sl) if sum(sl) else 1), sl)) for sl in l]
Shai
  • 111,146
  • 38
  • 238
  • 371
  • I am getting [, , ]. Can you have a direct ouput without the map? – Mat.S Jun 25 '17 at 06:35
  • @Mat.S apparently you are using python3. if you `list(map(...))` python will convert the map objects to lists. – Shai Jun 25 '17 at 06:37
  • Thanks, one last thing, how do you add a case that checks for division by zero and in those cases, the entries are just zero. – Mat.S Jun 25 '17 at 06:40
0

Using a couple of comprehensions as:

Code:

[[float(z)/sum(x) for z in x] for x in y]

Test Code:

y = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

print([[float(z)/sum(x) for z in x] for x in y])

Results:

[   [0.16666666666666666, 0.3333333333333333, 0.5], 
    [0.26666666666666666, 0.3333333333333333, 0.4], 
    [0.2916666666666667, 0.3333333333333333, 0.375]
]
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
0

It could be done as follows, using list comprehension:

vals = [[1,2,3],[4,5,6],[7,8,9]]
denoms = [sum(entries) for entries in vals]
fracs = [[Fraction(entry, denom) for entry in entries] for entries, denom in zip(vals, denoms)]
floats = [[entry/denom for entry in entries] for entries, denom in zip(vals, denoms)]

Here I first calculate the denominators as the sum of the individual sublists, then I divide each element in the sublists with their respective denominators.

Also, I give you the output both in fractional (fracs) and decimal (floats) form. Pick whichever suits your needs.

JohanL
  • 6,671
  • 1
  • 12
  • 26
0

Here we go:

list=[[1,2,3],[4,5,6],[7,8,9]] 
newList=[]
subList=[]
for el in list:
    for subEl in el:
        subList.append(subEl/sum(el))
    newList.append(subList)
    subList=[]
print(newList)   

Output is:

[[0.16666666666666666, 0.3333333333333333, 0.5], [0.26666666666666666, 0.3333333333333333, 0.4], [0.2916666666666667, 0.3333333333333333, 0.375]]

Rahul Raj
  • 3,197
  • 5
  • 35
  • 55