英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论