简体   繁体   English

函数内部函数,python递归列表

[英]function inside a function, python recursive on a list

def minimizeMaximumPair(lst):
    lst.sort()

    def compute(aList):
        if len(aList) != 0:
            return [(aList[0], lst[len(aList) - 1])].extend(compute(aList[1:len(aList) - 1]))
        return []

    return compute(lst)

When I get the the last recursion step I get an 当我得到最后一个递归步骤时,我得到一个

TypeError: 'NoneType' object is not iterable

I tried returning nothing, and a [] 我试着什么都没回来,而且[]

The issue is when you call .extend() . 问题是当你调用.extend()

Your compute function tries to return the value of .extend() , which is None . 您的compute函数尝试返回.extend()的值,即None Similar to .sort() , .extend() modifies the object itself, rather than returning a modified copy of the object. .sort()类似, .extend()修改对象本身,而不是返回对象的修改副本。 This is known as mutability. 这被称为可变性。 Here's some working code: 这是一些有效的代码:

def compute(aList):
    if len(aList) != 0:
        out = [(aList[0], lst[len(aList) - 1])]
        out.extend(compute(aList[1:len(aList) - 1]))
        return out
    return []

Instead of list.extend which returns None , you can use list.__iadd__ 而不是list.extend返回None ,你可以使用list.__iadd__

__iadd__ also extends the list inplace, but returns the list afterward __iadd__也将列表扩展__iadd__ ,但之后返回list

if you have an aversion to using special methods, you can use iadd from the operator module 如果您厌恶使用特殊方法,可以使用operator模块中的iadd

from operator import iadd

...

def compute(aList):
    if len(aList) != 0:
        return iadd([(aList[0], aList[-1])], compute(aList[1: -1]))
    return []

That's because extend is a function that doesn't return anything, it simply changes the list in-place. 这是因为extend是一个不返回任何内容的函数,它只是就地更改列表。 A possible solution is to use + instead: 一个可能的解决方案是使用+代替:

return [(aList[0], lst[len(aList) - 1])] + compute(aList[1:len(aList) - 1])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM