pythonmathstatisticsprobability

# Convert a list with a sum of 1 and keep the relations between the values

Assume there is a `list[int]` like this:

``````[0, 2, 3, 3, 0, 9]
``````

I want to convert it to `list[float]` with a sum of 1 and keep the relations between the values:

``````[a, b, c, d, e, f]

# a = e = 0
# c = d
# f = 4.5b = 3c = 3d
# a + b + c + d + e + f = 1

[0.0, x, 1.5x, 1.5x, 0.0, 4.5x]
``````

I guess there is a built-in function that does that in some modules like `math` or `statistics`, not sure what it is called.

Solution

• Not sure if an inbuilt function exists, but perhaps you can just use a list comprehension:

``````>>> input_list = [0, 2, 3, 3, 0, 9]
>>> total = sum(input_list)
>>> [x / total for x in input_list]
[0.0, 0.11764705882352941, 0.17647058823529413, 0.17647058823529413, 0.0, 0.5294117647058824]
``````

I thought you could use the walrus operator (`:=`) to do this in one line `[x / (total := sum(input_list)) for x in input_list]` and only calculate `sum(input_list)` once, but apparently, that is not the case.