Python - List Comprehension problem: do i need nested List Comprehension?

Viewed 62

I'm new in Python and I cannot do this simple exercise (i now it's simple but i cannot resolved it). I've been 4 year using many combinations, looking for help here in SO and others forums and nothing help to my problem, this is my nightmare:

letters_count = {
    'Alpha': [10, 12, 0, 1],
    'Beta': [15, 7, 9, 2],
    'Gamma': [6],
    'Delta': [2, 2, 4],
    'Eta': [9, 9, 9],
    }

I need to create a script that subtracts the mean for a given country from each success estimate for that country, only using List Comprehension (with parenthesis) and the output of that be similar at this:

[['Alpha', [4.25, 6.25, -5.75, -4.75]], 
 ['Beta', [6.75, -1.25, 0.75, -6.25]], 
 ['Gamma', [0]],
 ['Delta', [-0.66, -0.66, 1.33]],
 ['Eta', [0, 0, 0]]]

I would like to put some of my codes, but none of them works

3 Answers

Try this:

[[k,[v[i] - sum(v)/len(v) for i in range(len(v))]] for k, v in letters_count.items()]

or

[[key, [e-sum(value)/len(value) for e in value]] for key, value in letters_count.items()]

p.s Thanks, JohanL

If you are using python3.8, you can avoid doing the average more than once. You can use a variable ave (or mean) and get the distance of each element of the list from the mean. Don't forget to round off the answer into two decimal places. Note that the operator is := rather than =

letters_count = {
    'Alpha': [10, 12, 0, 1],
    'Beta': [15, 7, 9, 2],
    'Gamma': [6],
    'Delta': [2, 2, 4],
    'Eta': [9, 9, 9],
    }
result = [[letter, [round((ave - v), 2) for v in lst]] for letter, lst in letters_count.items() if (ave := sum(lst)/len(lst))]
print(result)

Result:

[['Alpha', [-4.25, -6.25, 5.75, 4.75]], 
 ['Beta', [-6.75, 1.25, -0.75, 6.25]], 
 ['Gamma', [0.0]], 
 ['Delta', [0.67, 0.67, -1.33]], 
 ['Eta', [0.0, 0.0, 0.0]]]

so instead of trying to do everything in one go at first, break the problem down.

first, you need to find the avg-adjusted values in each list. that will look something like:

adj_avg = lambda vals: [v - sum(vals) / len(vals) for v in vals] 

from there, it's pretty easy to add in the keys to make it into your desired output:

[[key, adj_avg(vals)] for key, vals in letters_count.items()]

which becomes:

[[key, [v - sum(vals) / len(vals) for v in vals]] for key, vals in letters_count.items()]
Related