[英]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)
.列表的平均值是sum(myList) / len(myList)
。
If you remove an element x
from myList
, the sum becomes sum(myList) - x
.如果从myList
删除元素x
,则总和变为sum(myList) - x
。 Now the mean of the remaining elements is (sum(myList) - x) / (len(myList) - 1)
现在剩余元素的平均值是(sum(myList) - x) / (len(myList) - 1)
For all elements:对于所有元素:
newList = [(sum(myList) - x) / (len(myList) - 1) for x in myList]
Or for O(n),或者对于 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:我找到了一种使用collections.deque
并“旋转”它的方法,并在循环的每次迭代中删除第一个元素:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.