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]]
CodePudding user response:
How about
L_avg=[sum(sublist)/len(sublist) if sublist else [] for sublist in L]
CodePudding user response:
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 x else [] for x in L
]
CodePudding user response:
You can try this:
L=[[], [1.3342713788981633], [1.3342713788981633], [0.40896852187708455,1,3]]
L_avg = [ sum(l)/len(l) if len(l) > 0 else [] for l in L ]
print(L_avg)
Explanation: this iterates over all the sublists in L
and calculates the average as the sum of the elements over the number of elements. The if-else
is necessary to handle the case when the sublist is empty, which would give a division by 0.
CodePudding user response:
If you think about how to do this in a for loop it'll make it easier to understand a comprehension.
for sl in L:
print(sum(sl)/len(sl) if sl > 0 else [])
So the comprehension is:
[sum(sl)/len(sl) if sl > 0 else [] for sl in L]
CodePudding user response:
Try this code:
L_avg = [sum(l)/len(l) if len(l)>0 else [] for l in L]
it would probably make more sense to return None
instead of []
when the list on computing the average is empty:
L_avg = [sum(l)/len(l) if len(l)>0 else None for l in L]
CodePudding user response:
You only be able to do this averaging if all your list members have values inside, in your case the first is empty, hence the error. It expected 2 parameters and got 0.
You can filter out the ones with len zero:
L_avg = [sum(item)/len(item) if len(item)>0 else [] for item in L]