在 Python 中对元组字典进行排序
我知道已经有很多关于 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 函数来访问该类的成员?
非常感谢
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 solution as I'm going to be sorting a rather large dataset.
My data basically looks like this at the moment:
a = {'a': (1, 2, 3), 'b': (3, 2, 1)}
I'm basically creating a word list in which I store each word along with some stats about it (n, Sigma(x), Sigma(x^2) )
I want to sort it based on a particular stat. So far I've been trying something along the lines of:
b = a.items()
b.sort(key = itemgetter(1), reverse=True)
I'm not sure how to control which index it is sorted based on when its effectively a list of tuples of tuples? I guess I effectively need to nest two itemgetter operations but not really sure how to do this.
If there's a better data structure I should be using instead please let me know. Should I perhaps create a small class/struct and then use a lambda function to access a member of the class?
Many Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
像这样的东西吗?
Something like this?
名称更容易使用并记住索引,所以我会选择一个类:
Names are easier to work with and remember that indices, so I would go with a class: