Sorting a dictionary of tuples in Python

后端 未结 2 1422
野性不改
野性不改 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)
    
    0 讨论(0)
  • 2021-02-20 14:41

    Something like this?

    >>> a = {'a': (1, 2, 3), 'b': (3, 2, 1)}
    >>> b = a.items()
    >>> b
    [('a', (1, 2, 3)), ('b', (3, 2, 1))]
    >>> b.sort(key=lambda x:x[1][2])  # sorting by the third item in the tuple
    >>> b
    [('b', (3, 2, 1)), ('a', (1, 2, 3))]
    
    0 讨论(0)
提交回复
热议问题