Reputation: 36604
I want to compare every element of the list to the rest of the elements. For this, I need to iteratively exclude one element. Specifically, I want to calculate the mean of all elements when one value is removed. E.g.:
mylist = [1, 2, 3, 4]
Mean values:
[2, 3, 4] = 3 (excludes 1)
[1, 3, 4] = 2.66 (excludes 2)
[1, 2, 4] = 2.44 (excludes 3)
[1, 2, 3] = 2 (excludes 4)
Is there an intuitive way of doing this, without something like
[mylist[i-1:i] + mylist[i+1:] for i in range(len(mylist))]?
Upvotes: 2
Views: 100
Reputation: 36604
I found a way using a collections.deque
and "rotate" it, and removing the first element at every iteration of the loop:
mylist = [1, 2, 3, 4]
from collections import deque
for i in range(len(mylist)):
d = deque(mylist)
d.rotate(-i)
first, *rest = d
print(f'{rest}: {sum(rest)/len(rest):.2f}')
[2, 3, 4]: 3.00
[3, 4, 1]: 2.67
[4, 1, 2]: 2.33
[1, 2, 3]: 2.00
Upvotes: 1
Reputation: 25489
Maths to the rescue!
The mean of a list is sum(myList) / len(myList)
.
If you remove an element x
from myList
, the sum becomes sum(myList) - x
. Now the mean of the remaining elements is (sum(myList) - x) / (len(myList) - 1)
For all elements:
newList = [(sum(myList) - x) / (len(myList) - 1) for x in myList]
Or for O(n),
s = sum(myList)
newLen = len(myList) - 1
newList = [(s - x) / newLen for x in myList]
Upvotes: 7