简体   繁体   English

使用元组和operator.itemgetter对字典进行排序

[英]Sorting dictionary using a tuple and operator.itemgetter

I am before my last milestone preparing suitable output. 我在最后一个里程碑准备合适的输出之前。 Its quite simple, I think, but my approach doesn't work: 我认为这很简单,但是我的方法不起作用:

Given an dictionary like 给定像这样的字典

mydict = {x1: (val1, dist1, (lat1, lon1)), x2: (val2, dist2, (lat2, lon2)), ...}

I tried to sort this in a nested way in an array, first using the "values" and if equals, sorting for "dist". 我试图以嵌套方式在数组中对此进行排序,首先使用“值”,如果相等,则对“ dist”进行排序。

However, I did my homework and tried it using this way: 但是,我做了家庭作业,并尝试使用这种方式:

import operator
s = sorted(mydict.iteritems(), key=operator.itemgetter(1))

The thing is that if the sort method would be appliable to tuples, it would be quite easy, because it's already in the right order. 事实是,如果sort方法适用于元组,那将非常容易,因为它的顺序已经正确。

Unfortunately I get: 不幸的是我得到:

'list' object is not callable “列表”对象不可调用

Do you have an idea? 你有想法吗?

您是否可能重写了用列表值sorted的名称?

The thing is that if the sort method would be appliable to tuples, it would be quite easy 问题是,如果sort方法适用于元组,那将非常容易

sorted() works perfectly fine on a list of tuples, in which case it uses a lexicographic ordering . sorted()在元组列表上工作得很好,在这种情况下,它使用字典顺序

(a,b) ≤ (a′,b′) if and only if a < a′ or (a = a′ and b ≤ b′). 当且仅当a <a'或(a = a'并且b≤b')时(a,b)≤(a',b')。

This can be expanded to any number of dimensions. 可以扩展到任意数量的尺寸。

>>> sorted([(10, 1), (5, 3), (6, 5), (3, 2), (5, 10)])
[(3, 2), (5, 3), (5, 10), (6, 5), (10, 1)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM