简体   繁体   English

对对象字典进行排名的最佳方法是什么?

[英]What is the best approach to rank a dictionary of objects?

Given the following classes:给定以下类:

class Comparison():

    def __init__(self, value):
        self.value = value
        self.rank = 0

class Comparisons(dict):

    def __init__(self):
        super(Comparisons, self).__init__()

    def rank(self):
        # Method to examine each Comparison instance and
        # assign Comparison.rank based on Comparison.value

What is an efficient way for the rank() method to examine the objects and assign a rank? rank()方法检查对象并分配等级的有效方法是什么? For example:例如:

comparisons = Comparisons()

# store some Comparison instances
comparisons['one'] = Comparison(10)
comparisons['two'] = Comparison(5)
comparisons['three'] = Comparison(1)

# function to rank the comparisons
comparisons.rank()

print(comparisons['one'].rank)
print(comparisons['two'].rank)
print(comparisons['three'].rank)

Returns:回报:

3
2
1

If the rank() method could handle ties, that would be even more beneficial.如果rank()方法可以处理平局,那将更加有益。

This looks like the most intuitive (naive?) way:这看起来像最直观(天真?)的方式:

def rank(self):
    sorted_comparisons = sorted(self.values(), key=lambda c: c.value)
    for rank, comparison in enumerate(sorted_comparisons, 1):
        comparison.rank = rank

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM