我一直希望有人会在 Stackoverflow 上问这个具体问题,但因为还没有人问过:我如何制作一个像枚举这样的迭代器来对分数进行排名,这样平局就不会增加排名?
例如,我想以 score
, name
的形式给出分数和名称的排序列表的排名。
scores = [(42, 'Adams'), (42, 'Douglas'), (41, 'Aaron'),
(41, 'Hall'), (39, 'Python')]
我可以使用枚举来获取每个名称的位置,
for i, (s, name) in enumerate(scores, 1):
print i, s, name
但是即使有两个或更多的分数相同,每行都会降低排名。这是 ordinal ranking as described in Wikipedia .
1 42 Adams
2 42 Douglas
3 41 Aaron
4 41 Hall
5 39 Python
如果我知道我需要相同的函数 API 以便它是枚举的直接替代品,那么如果它们与分数并列,我如何在不增加的情况下完成此操作?这被描述为standard competition ranking in Wikipedia .
这是 enumerate
equivalency written in Python from the documentation :
def enumerate(sequence, start=0):
n = start
for elem in sequence:
yield n, elem
n += 1
最佳答案
当我第一次开始我目前工作的地方并通过培训 Material 运送时,我遇到了这个具体问题,但是当我攀登排名时我感到沮丧,因为我的排名低于与我并列的其他人。这是我对代码库的第一次贡献,但收紧了一点(因为,令人尴尬的是,我第一次没有使用 enumerate
!)
我的解决方案是使用我最初在 enumerate equivalency code in the documentation 上建模的生成器(见上面的问题)。
def rank(sequence, start=0): #as in enumerate()
'''
rank generator function handles score ties,
same API as enumerate for drop-in replacement
assumes given a sorted sequence of two-tuples
of scores and names (or some other description)
'''
rank = start
previous_score = None # need to initialize
for n, (score, name) in enumerate(sequence, start):
if score != previous_score: #rank up if not tie
rank = n
previous_score = score
yield rank, (score, name) #rank unmodified if a tie.
和用法:
for i, (s, name) in rank(scores, 1):
print i, s, name
将打印:
1 42 Adams
1 42 Douglas
3 41 Aaron
3 41 Hall
5 39 Python
关于python - 枚举的直接替换,对传递的元素进行排名,这样关系就不会增加排名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24563982/