简体   繁体   中英

Iteratively compare one element to all others in a Python list

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. Eg:

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))]?

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]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM