Sorting a dictionary of tuples in Python

后端 未结 2 1423
野性不改
野性不改 2021-02-20 13:55

I know there\'s tonnes of questions on python sorting lists/dictionaries already, but I can\'t seem to find one which helps in my case, and i\'m looking for the most efficient s

2条回答
  •  感情败类
    2021-02-20 14:23

    Names are easier to work with and remember that indices, so I would go with a class:

    class Word(object):     # don't need `object` in Python 3
        def __init__(self, word):
            self.word = word
            self.sigma = (some calculation)
            self.sigma_sq = (some other calculation)
        def __repr__(self):
            return "Word(%r)" % self.word
        def __str__(self):
            return self.word
        @property
        def sigma(self):
            return self._sigma
        @sigma.setter               # requires python 2.6+
        def sigma(self, value):
            if not value:
                raise ValueError("sigma must be ...")
            self._sigma = value
    
    word_list = [Word('python'), Word('totally'), Word('rocks')]
    word_list.sort(key=lambda w: w.sigma_sq)
    

提交回复
热议问题