有人能解释一下为什么排序函数返回 “None” 吗?

huangapple go评论74阅读模式
英文:

Can someone please explain to me why sorting function returns "None"

问题

以下是您要翻译的代码部分:

numbers = input("Enter numbers.")

numbersArray = numbers.split()

realNumbersArray = []

for x in numbersArray:
    realNumbersArray.append(int(x))
    print(x)

print(len(realNumbersArray))

print(realNumbersArray.sort())

关于为什么第二个打印命令一直返回"None",可以有如下解释:

在Python中,list.sort() 方法用于对列表进行原地排序,也就是说它会直接修改列表而不返回一个新的排序后的列表。因此,realNumbersArray.sort() 返回的是None,因为它不返回排序后的列表,而只是对realNumbersArray 进行了排序。如果您想要打印排序后的列表,可以这样修改代码:

numbers = input("Enter numbers.")

numbersArray = numbers.split()

realNumbersArray = []

for x in numbersArray:
    realNumbersArray.append(int(x))
    print(x)

print(len(realNumbersArray))

realNumbersArray.sort()  # 对列表进行排序,不返回任何值

print(realNumbersArray)  # 打印排序后的列表
英文:
numbers = input("Enter numbers.")

numbersArray = numbers.split()

realNumbersArray = []



for x in numbersArray:
 realNumbersArray.append(int(x))
 print(x)
 
print(len(realNumbersArray))

print(realNumbersArray.sort())

Can someone explain why the second print command keeps returning "None"?

答案1

得分: 2

.sort()方法会原地对数组进行排序,但返回值是None。你的realNumbersArray现在已经排序好了,如果你打印它,你会看到列表按照预期排序了。

你想要这样做:

print(len(realNumbersArray))
realNumbersArray.sort()    # 数组已经排序
print(realNumbersArray)    # 打印已排序的数组
英文:

the .sort() sorts the array in place but returns None. your realNumbersArray is now sorted and if you print it, you will see the list sorted as expected.

You want to do this:

print(len(realNumbersArray))
realNumbersArray.sort()    # Array is now sorted
print(realNumbersArray)    # Print sorted array

答案2

得分: 2

作为对这个答案的替代方案,如果您想要输出一个已排序的数组版本,但想改变原始数组,您可以这样做:

print(len(realNumbersArray))
print(sorted(realNumbersArray))
print(realNumbersArray)

这里的重要概念是,函数/方法执行的操作和它返回的内容通常并不相同。.sort()是设计用于您想要对数组等进行排序但不立即查看排序值的情况;这类函数通常会返回None。sorted()用于您想要创建已排序版本并立即执行某些操作,而不更改原始数据的情况。

英文:

As an alternative to this answer, if you want to output a sorted version of the array but you don't want to alter the original array, you can do:

print(len(realNumbersArray))
print(sorted(realNumbersArray))
print(realNumbersArray)

The important concept here is that what a function/method does and what it returns often aren't the same thing. The .sort() is designed for cases where you want to sort an array/etc. but don't immediately want to look at the sorted values; functions of that kind will often return None. sorted() is for cases where you want to create a sorted version, and do something with it immediately, without changing the original.

huangapple
  • 本文由 发表于 2023年6月16日 08:54:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76486341.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定