简体   繁体   English

迭代地将一个元素与 Python 列表中的所有其他元素进行比较

[英]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.

相关问题 将列表中的每个元素与其他元素进行比较 - Compare each element in a list to all others 如何将一个列表的元素与其他两个列表的元素进行比较,并为 python 中的每个元素生成 output? - How to compare the elements of one list with those of two others and generate an output for every element in python? 将每个列表的元素与列表中的其他元素进行比较 - Compare each list's element with others in the list 有没有办法在python中迭代更改列表元素的position? - Is there a way to change the position of an element of a list iteratively in python? Python将文件中的每一行与其他所有行进行比较 - Python compare every line in file with all others 清单中的Python Compare元素与上一个和下一个 - Python Compare element in a list with the previous one and the next one 如何比较列表中的一个项目与此列表中的所有其他项目python - how to compare one item in a list with all the other items in this list, python python,列表比较,ValueError:具有多个元素的数组的真值不明确。 使用a.any()或a.all() - python, list compare, ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 正则表达式与列表中的元素迭代匹配 - Regex match with element in list iteratively Python - 比较列表元素(如果存在) - Python - Compare list element if exist
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM