I have a list L. I want to average elements of each list within this list. But I am getting an error. I present the expected output.
L=[[], [1.3342713788981633], [1.3342713788981633], [0.40896852187708455,1,3]]
L_avg=[(i+j)/len[i,j] for [i,j] in L]
print(L_avg)
The error is
in <listcomp>
L_avg=[(i+j)/len[i,j] for [i,j] in L]
ValueError: not enough values to unpack (expected 2, got 0)
The expected output is
L_avg=[[], [1.3342713788981633], [1.3342713788981633], [(0.40896852187708455+1+3)/3]]
>Solution :
You’re getting an error because of this:
for [i,j] in L
In this way you are trying to assign elements of L to [i,j] but expressions such as [i,j]=[] or [i,j]=[1.3342713788981633] just make no sense.
Here’s what you should do instead
L=[[], [1.3342713788981633], [1.3342713788981633], [0.40896852187708455,1,3]]
L_avg = [
[sum(x)/len(x)] if len(x)>0 else [] for x in L
]