简体   繁体   English

为什么(dictionary.keys())。sort()在python中不起作用?

[英]Why (dictionary.keys()).sort() is not working in python?

I'm new to Python and can't understand why a thing like this does not work. 我是Python的新手,无法理解为什么这样的东西不起作用。 I can't find the issue raised elsewhere either. 我也找不到其他地方提出的问题。

toto = {'a':1, 'c':2 , 'b':3}
toto.keys().sort()           #does not work (yields none)
(toto.keys()).sort()         #does not work (yields none)
eval('toto.keys()').sort()   #does not work (yields none)

Yet if I inspect the type I see that I invoke sort() on a list, so what is the problem.. 然而,如果我检查类型,我看到我在列表上调用sort(),那么问题是什么..

toto.keys().__class__     # yields <type 'list'>

The only way I have this to work is by adding some temporary variable, which is ugly 我有这个工作的唯一方法是添加一些丑陋的临时变量

temp = toto.keys()
temp.sort()

What am I missing here, there must be a nicer way to do it. 我在这里缺少什么,必须有一个更好的方法来做到这一点。

sort() sorts the list in place . sort()对列表进行排序。 It returns None to prevent you from thinking that it's leaving the original list alone and returning a sorted copy of it. 它返回None以防止您认为它仅保留原始列表并返回它的已排序副本。

sorted(toto.keys())

Should do what you want. 应该做你想做的。 The sort method you're using sorts in place and returns None. 您正在使用的排序方法就地排序并返回None。

sort() method sort in place, returning none . sort()方法就地排序,返回none You have to use sorted(toto.keys()) which returns a new iterable, sorted. 您必须使用sorted(toto.keys())返回一个新的iterable,已排序。

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

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