在Python中排序元组字典

12 投票
2 回答
16566 浏览
提问于 2025-04-17 01:48

我知道关于Python排序列表和字典的问题已经很多了,但我找不到一个能解决我这个情况的。我希望能找到一个最有效的解决方案,因为我需要排序的数据集比较大。

目前我的数据大概是这样的:

a = {'a': (1, 2, 3), 'b': (3, 2, 1)}

我基本上是在创建一个单词列表,里面存储每个单词以及一些相关的统计数据(比如n、Sigma(x)、Sigma(x^2))。

我想根据某个特定的统计数据来排序。到目前为止,我尝试过一些方法:

b = a.items()
b.sort(key = itemgetter(1), reverse=True)

我不太确定在处理一个包含元组的列表时,如何控制根据哪个索引进行排序?我想我需要嵌套两个itemgetter操作,但我不太确定该怎么做。

如果有更好的数据结构可以使用,请告诉我。我是否应该创建一个小类或者结构体,然后用一个lambda函数来访问这个类的成员?

非常感谢!

2 个回答

1

用名字来处理东西比用数字索引要简单得多,也更容易记住。所以我建议使用一个类:

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)
9

像这样吗?

>>> 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))]

撰写回答