【问题标题】:Sorting a dictionary of tuples in Python在 Python 中对元组字典进行排序
【发布时间】:2011-11-13 01:26:42
【问题描述】:

我知道关于 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 函数来访问该类的成员?

非常感谢

【问题讨论】:

    标签: python sorting dictionary tuples


    【解决方案1】:

    这样的?

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

    【讨论】:

    • 是的,非常感谢!但是我在某处读到 itemgetter 比使用 lambda 函数更快,因为它的 C 编译?如果我不能使用 itemgetter,那么这个解决方案很好。
    • 在你有一个工作程序并完成单元测试之前不要担心性能。如果最终的正确程序太慢,则对其进行分析,并优化慢位。
    • 好点 :) 如果它太慢,我可能会用 C 重写它,谢谢指点 :)
    • 这是如何工作的?我得到:AttributeError: 'dict' object has no attribute 'sort'
    【解决方案2】:

    名称更容易使用并记住索引,所以我会选择一个类:

    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)
    

    【讨论】:

    • 这很有帮助,谢谢!不要假设你在类 def 中明确定义了每个变量的类型?
    • @technosites 如果“每个变量的类型”是指 int vs str vs float 等,您可以使用属性进行数据验证等等。
    • @technosites 添加了属性示例
    猜你喜欢
    • 2018-10-19
    • 2017-08-21
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 2013-09-13
    • 2017-07-12
    • 2014-11-10
    相关资源
    最近更新 更多