簡體   English   中英

迭代地將一個元素與 Python 列表中的所有其他元素進行比較

[英]Iteratively compare one element to all others in a Python list

我想將列表中的每個元素與其余元素進行比較。 為此,我需要迭代地排除一個元素。 具體來說,我想在刪除一個值時計算所有元素的平均值。 例如:

mylist = [1, 2, 3, 4]

平均值:

[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)

有沒有一種直觀的方法來做到這一點,沒有像

[mylist[i-1:i] + mylist[i+1:] for i in range(len(mylist))]?

數學來拯救!

列表的平均值是sum(myList) / len(myList)

如果從myList刪除元素x ,則總和變為sum(myList) - x 現在剩余元素的平均值是(sum(myList) - x) / (len(myList) - 1)

對於所有元素:

newList = [(sum(myList) - x) / (len(myList) - 1) for x in myList]

或者對於 O(n),

s = sum(myList)
newLen = len(myList) - 1 
newList = [(s - x) / newLen for x in myList]

我找到了一種使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM