下面是一个使用方案的变化内置有一个自定义的比较函数sorted()
功能。 (它可能看起来像很多代码,但其中很大一部分只是为了设置一个有些现实的测试用例。)
from functools import cmp_to_key
import random
random.seed(13) # Gets consistent "random" ordering during testing.
class User:
def __init__(self, name, id):
self.name = name
self.id = id
def __repr__(self):
return '{}({!r}, id={!r})'.format(self.__class__.__name__, self.name, self.id)
@cmp_to_key # Converts cmp function to a key function.
def cmp(x, y):
""" Return -1 if the position of User x in list_of_ids < index of User y
otherwise return 1.
"""
p1, p2 = -1, -1
try:
p1 = list_of_ids.index(x.id)
p2 = list_of_ids.index(y.id)
except ValueError:
pass
return -1 if p1 < p2 else 1
list_of_ids = [3, 2, 5, 8, 9]
# Create a random list of users with these ids.
shuffled_ids = random.sample(list_of_ids, k=len(list_of_ids))
users = [User(name, id) for name, id in zip(['Andy', 'Simon', 'Nick', 'John',
'Roger'], shuffled_ids)]
print('Desired id order:', list_of_ids)
print()
print(' Before:', users)
ordered_result = sorted(users, key=cmp)
print('Ordered:', ordered_result)
输出:
Desired id order: [3, 2, 5, 8, 9]
Before: [User('Andy', id=5), User('Simon', id=9), User('Nick', id=8), User('John', id=3), User('Roger', id=2)]
Ordered: [User('John', id=3), User('Roger', id=2), User('Andy', id=5), User('Nick', id=8), User('Simon', id=9)]
这不是很清楚你的要求。 –
结果列表,它在哪里?你是怎么计算的? –
@martineau我很确定它不是重复的,至少不是你引用的Q.观察一下_unsorted_列表给出的期望顺序是如何产生的,这是一个非常不同的问题。特别是,仅将属性作为关键字进行排序不是解决方案。 –