Python列表排序代码执行后输出'None'的原因咨询
问题原因及解决方案
这个问题我之前排查过,本质是对Python列表排序方法的返回值逻辑理解有误,另外代码里还有个小笔误需要先修正~
核心问题:list.sort()的返回值是None
Python里的列表sort()方法是原地排序——它会直接修改你调用它的原列表,不会生成并返回一个新的排序后的列表,所以它的返回值固定是None。你直接print(total.sort())的时候,打印的就是这个返回值,自然会输出None。
另外代码里还有个变量名错误:total = lopA1+lopA2应该改成total = ClassA1+ClassA2,不然会报变量未定义的错误。
两种修正方案
方案1:先执行原地排序,再打印原列表
先调用sort()修改列表,之后直接打印修改后的total即可:
ClassA1=[7.8,5.6,8.7,8.9,9,9.5] ClassA2=[6.0,6.5,9.3,9.2,7.5] choice=int(input("Press 1 if you want to sort the scoreboard in ascending order.\nPress 2 if you want to sort the scoreboard in descending order.")) total = ClassA1 + ClassA2 # 修正变量名错误 if choice == 1: total.sort() print(total) elif choice == 2: total.sort(reverse=True) print(total)
方案2:使用sorted()函数(推荐,不修改原列表)
sorted()函数会生成并返回一个新的排序后的列表,不会改动原列表,直接打印它的返回值就可以得到正确结果:
ClassA1=[7.8,5.6,8.7,8.9,9,9.5] ClassA2=[6.0,6.5,9.3,9.2,7.5] choice=int(input("Press 1 if you want to sort the scoreboard in ascending order.\nPress 2 if you want to sort the scoreboard in descending order.")) total = ClassA1 + ClassA2 if choice == 1: print(sorted(total)) elif choice == 2: print(sorted(total, reverse=True))
内容的提问来源于stack exchange,提问作者khởi lè
相关产品推荐
相关产品推荐

