简体   繁体   English

当值为列表时,dict(sorted(dictionary.items(), key=operator.itemgetter(1)) 并不总是返回有序的dict

[英]dict(sorted(dictionary.items(), key=operator.itemgetter(1)) does not always return a ordered dict when the value is a list

I have a dict:我有一个字典:

count2:defaultdict(<class 'list'>, {'i': [3, 2, 2, 1], 'w': [2, 2], 'p': [2, 2], 'd': [2, 2], 'm': [2, 2], 'y': [2, 2, 2, 1], 'x': [2, 2, 4, 1], 'j': [2, 2], 'o': [2, 1], 'r': [2, 1]})

when I try to sort it by using当我尝试通过使用对其进行排序时

ordered = dict(sorted(count2.items(), key=operator.itemgetter(1), reverse=True)) 

It not always sorts it like I want it to sort.它并不总是像我想要的那样对其进行排序。 (the value must have the biggest number and then descend) so it returns this: (该值必须具有最大的数字,然后下降)所以它返回:

orderedStart:{'i': [3, 2, 2, 1], 'x': [2, 2, 4, 1], 'y': [2, 2, 2, 1], 'w': [2, 2], 'p': [2, 2], 'd': [2, 2], 'm': [2, 2], 'j': [2, 2], 'o': [2, 1], 'r': [2, 1]}

everything is right except for that x should be in front of i since 4 > 3 .一切都是正确的,除了x应该在i前面,因为4 > 3 Are some indexes more prioritized?某些索引是否更优先?

To facilitate the users, here is an Example of a well sorted list using the same code.为了方便用户,这里是一个使用相同代码的良好排序列表的示例。

Before:前:

count2:defaultdict(<class 'list'>, {'r': [2, 2, 2, 1], 'g': [2, 1], 'e': [3, 1], 'n': [5, 1], 't': [4, 1], 'i': [2, 1], 'o': [5, 1], 'm': [2, 1]})

After:后:

{'n': [5, 1], 'o': [5, 1], 't': [4, 1], 'e': [3, 1], 'r': [2, 2, 2, 1], 'g': [2, 1], 'i': [2, 1], 'm': [2, 1]}

You misunderstand how python compares tuples.您误解了 python 如何比较元组。 You have asked it to compare [3, 2, 2, 1] and [2, 2, 4, 1] .您已要求它比较[3, 2, 2, 1][2, 2, 4, 1] Since 3 > 2, it comes first.由于 3 > 2,它首先出现。

Python uses "lexicographic comparison", which is identical to the way you look up words in a dictionary. Python 使用“字典比较”,这与您在字典中查找单词的方式相同。 First you compare the first letters.首先你比较第一个字母。 If they are different, you're done;如果它们不同,那么您就完成了; if they are different, you look at the second letter.如果它们不同,请查看第二个字母。 And so forth.等等。

When you compare lists, they're compared lexicographically, so the first element takes precedence, then the second, and so on.当您比较列表时,它们会按字典顺序进行比较,因此第一个元素优先,然后是第二个元素,依此类推。 If you want the largest list element to take precedence, compare sorted lists.如果您希望最大的列表元素优先,请比较排序列表。

ordered = dict(sorted(count2.items(), key=lambda item: sorted(item[1], reverse=True), reverse=True)) 

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

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