python sort返回none,为什么'.sort()'在Python中导致列表为'None'?

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)

I have also tried

def LongestPath(T):

return[len(y) for y in [Ancestors(T,x) for x in OrdLeaves(T)] ].sort().pop()

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.

解决方案

Simply remove the assignment from

result = result.sort()

leaving just

result.sort()

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 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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值