简体   繁体   English

Python中的排序列表导致错误

[英]Sorting list in Python causes error

I'm having a problem sorting list in Python here's my code: 我在Python中有一个问题排序列表,这是我的代码:

lista = [ 1, .89, .65, .90]

for x in lista.sort():
    print (x)

Error is: 错误是:

TypeError: 'NoneType' object is not iterable

The sort method sorts the list in-place; sort方法对列表进行原位sort it always returns None . 它总是返回None What you can do: 你可以做什么:

lista = [ 1, .89, .65, .90]
lista.sort()

for x in lista:
    print (x)

Or, as @Delgan pointed out, you can use the sorted function, which returns the sorted list: 或者,就像@Delgan指出的那样,您可以使用已sorted函数,该函数返回已排序的列表:

lista = [ 1, .89, .65, .90]

for x in sorted(lista):
    print (x)

.sort() doesn't return anything. .sort()不返回任何内容。 If you want to modify the list to be sorted you can do 如果要修改要排序的列表,可以执行

lista = [ 1, .89, .65, .90]
lista.sort()
for x in lista:
    print (x)

or if you want to keep the list in the original order you can use sorted which returns a new list of the sorted elements: 或者,如果您想使列表保持原始顺序,则可以使用sorted ,它返回一个新的已排序元素列表:

lista = [ 1, .89, .65, .90]

for x in sorted(lista):
    print (x)

list.sort() only change the list but return None, you need: list.sort()仅更改列表,但返回None,您需要:

lista = [1, .89, .65, .90]
lista.sort()

for x in lista:
    print(x)

Or simply use sorted() : 或者简单地使用sorted()

lista = [1, .89, .65, .90]

for x in sorted(lista):
    print (x)

sorted() return a new list but sorted, note that it doesn't change the current list. sorted()返回一个新列表但已排序,请注意它不会更改当前列表。

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

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