为什么 '.sort()' 导致列表在 Python 中为 'None'? [英] Why does '.sort()' cause the list to be 'None' in Python?

查看:39
本文介绍了为什么 '.sort()' 导致列表在 Python 中为 'None'?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对 int 的 Python 列表进行排序,然后使用 .pop() 函数返回最高的一个.我试过用不同的方式写方法:

I am attempting to sort a Python list of ints 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'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆