如果您使用Python> = 3.4,則可以使用statistics.median_low()
。
from random import randrange
from statistics import median_low
a = [[randrange(8) for _ in range(7)] for _ in range(10)]
print("unsorted")
for item in a:
print(item)
a.sort(key=median_low)
print("\nsorted")
for item in a:
print(item)
輸出:
unsorted
[4, 2, 2, 1, 4, 7, 4]
[2, 2, 2, 7, 5, 5, 6]
[3, 0, 0, 5, 5, 3, 1]
[4, 7, 6, 2, 6, 7, 3]
[4, 7, 7, 1, 2, 7, 7]
[6, 2, 6, 5, 6, 7, 2]
[7, 1, 6, 0, 0, 7, 1]
[0, 5, 1, 2, 1, 7, 7]
[2, 7, 6, 7, 5, 4, 7]
[6, 5, 2, 3, 5, 0, 3]
sorted
[7, 1, 6, 0, 0, 7, 1]
[0, 5, 1, 2, 1, 7, 7]
[3, 0, 0, 5, 5, 3, 1]
[6, 5, 2, 3, 5, 0, 3]
[4, 2, 2, 1, 4, 7, 4]
[2, 2, 2, 7, 5, 5, 6]
[4, 7, 6, 2, 6, 7, 3]
[6, 2, 6, 5, 6, 7, 2]
[2, 7, 6, 7, 5, 4, 7]
[4, 7, 7, 1, 2, 7, 7]
EDIT充分替代的解決方案:
考慮排序的列表如下: 1.查找列表的median_low並將其移動到的前名單 2.查找列表[1:]的median_low並將其移至第二個地點 3.查找列表[2:]的中位數下降...
您可以按中位數值對原始列表進行排序,也可以創建按中位值對元素進行排序的鍵。
def def keyfunc(x):
t = x[:]
return [t.pop(t.index(median_low(t))) for _ in range(len(t))]
a = [
[4, 2, 2, 1, 4, 7, 4],
[2, 2, 2, 7, 5, 5, 6],
[3, 0, 0, 5, 5, 3, 1],
[7, 1, 6, 0, 0, 6, 1], # tie for first four rounds, but then wins
[4, 7, 6, 2, 6, 7, 3],
[6, 2, 6, 5, 6, 7, 2],
[7, 1, 6, 0, 0, 7, 1], # tie for first four rounds
[0, 5, 1, 2, 1, 7, 7],
[2, 7, 6, 7, 5, 4, 7],
[6, 5, 2, 3, 5, 0, 3]
]
a.sort(key=keyfunc)
print("\nsorted")
for item in a:
print(item)
輸出:
sorted
[7, 1, 6, 0, 0, 6, 1]
[7, 1, 6, 0, 0, 7, 1]
[0, 5, 1, 2, 1, 7, 7]
[3, 0, 0, 5, 5, 3, 1]
[6, 5, 2, 3, 5, 0, 3]
[4, 2, 2, 1, 4, 7, 4]
[2, 2, 2, 7, 5, 5, 6]
[4, 7, 6, 2, 6, 7, 3]
[6, 2, 6, 5, 6, 7, 2]
[2, 7, 6, 7, 5, 4, 7]
該比較函數沒有意義,因爲您使用中值作爲列表中的索引,但值的中值可能不是有效的索引。此外,即使它有效,它也會改變你的列表,這可能不是你想要的。請描述你想如何排序你的列表。 – BrenBarn
嗯,我認爲只要所有的數值都不相等,中位數的上限就提供了一個有效的指數?爲了避免變更列表,我應該先複製它們?這個想法是從大多數遊戲中實現打破平局的算法:https://en.wikipedia.org/wiki/Majority_judgment#Example_application –
如果你的列表是[[100,200,300]],那麼中位數是200,但200不是列表中的有效索引。 – BrenBarn