如果您使用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