问题描述
我正在尝试对int
的Python列表进行排序,然后使用.pop()
函数返回最高的列表.我尝试过用不同的方式编写方法:
I am attempting to sort a Python list of int
s and then use the .pop()
function to return the highest one. I have tried a writing the method in different ways:
def LongestPath(T):
paths = [Ancestors(T,x) for x in OrdLeaves(T)]
#^ Creating a lists of lists of ints, this part works
result =[len(y) for y in paths ]
#^ Creating a list of ints where each int is a length of the a list in paths
result = result.sort()
#^meant to sort the result
return result.pop()
#^meant to return the largest int in the list (the last one)
我也尝试过
def LongestPath(T):
return[len(y) for y in [Ancestors(T,x) for x in OrdLeaves(T)] ].sort().pop()
在两种情况下,.sort()
都会导致列表为None
(不具有.pop()
函数并返回错误).当我删除.sort()
时,它可以正常工作,但由于列表未排序,因此不会返回最大的int
.
In both cases .sort()
causes the list to be None
(which has no .pop()
function and returns an error). When I remove the .sort()
it works fine but does not return the largest int
since the list is not sorted.
推荐答案
只需从中删除作业
result = result.sort()
只留下
result.sort()
sort
方法就地工作(它修改了现有列表),因此不需要赋值,并且它返回None
.将结果分配给列表名称时,就是在分配None
.
The sort
method works in-place (it modifies the existing list), so no assignment is necessary, and it returns None
. When you assign its result to the name of the list, you're assigning None
.
可以轻松地(并且更有效地)将其编写为单行代码:
It can easily (and more efficiently) be written as a one-liner:
max(len(Ancestors(T,x)) for x in OrdLeaves(T))
max
在线性时间O(n)中运行,而排序为O(nlogn).您也不需要嵌套列表推导,只需一个生成器表达式就可以.
max
operates in linear time, O(n), while sorting is O(nlogn). You also don't need nested list comprehensions, a single generator expression will do.
这篇关于为什么'.sort()'在Python中导致列表为'None'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!