【发布时间】:2012-04-04 08:22:10
【问题描述】:
我正在尝试对 ints 的 Python 列表进行排序,然后使用 .pop() 函数返回最高的列表。我尝试过以不同的方式编写方法:
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,因为列表未排序。
【问题讨论】:
-
有什么理由不使用
max()? -
hc_,当我这样做时,我会收到
AttributeError: 'list' object has no attribute 'max' -
那是因为
max()是一个函数,而不是list方法。 -
来自 Python documentation:“您可能已经注意到,仅修改列表的插入、删除或排序等方法没有打印返回值——它们返回默认值 None。这是Python 中的所有可变数据结构。”