将变量指定为列表而不在函数中覆盖它 [英] Designate a variable as a list without overwriting it in a function

查看:104
本文介绍了将变量指定为列表而不在函数中覆盖它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个函数,可以将嵌套列表展平为普通列表.

I created a function that will flatten a nested list into an ordinary list.

outputarray = []

def flattenarray(x):
    for elmt in x:
        if isinstance(elmt, float) or isinstance(elmt, int):
            outputarray.append(elmt)
        elif isinstance(elmt, list):
            flattenarray(elmt)
    return outputarray

上面的方法很完美,但是我试图在函数中包含"outputarray"变量,但是当我这样做时,递归步骤将把outputarray列表改写为空列表.

The above works perfectly, but I am trying to have the "outputarray" variable inside the function, but when I do, the recursion step will overwrite the outputarray list back into an empty list.

我该如何在函数内部指定一个列表,同时又能在不递归的情况下将其追加到列表中?

How can I make this work to designate a list inside the function and at the same time be able to append to it without overwriting it during recursion?

推荐答案

您将要在函数中创建输出数组.一种进行方式是在递归步骤中传递输出容器:

You will want to create the output array from within the function. One way to proceed is to pass the output container along in the recursive step:

def flattenarray(x, outputarray=None):
    if outputarray is None:
        outputarray = []
    for elmt in x:
        if isinstance(elmt, float) or isinstance(elmt, int):
            outputarray.append(elmt)
        elif isinstance(elmt, list):
            flattenarray(elmt, outputarray=outputarray)
    return outputarray

更Python化的方法是使拼合器逐个生成项目.请注意,isinstance可以接受类型的元组,因此您只需调用一次即可.

A more Pythonic approach is for the flattener to yield the items one-by-one. Note that isinstance can accept a tuple of types, so you only need to call it once.

def flatten(x):
    for elmt in x:
        if isinstance(elmt, (int, float, str, bytes)):
            yield elmt
        else:
            yield from flatten(elmt)

更正确的鸭式实现:

def flatten(x):
    try:
        it = iter(x)
    except TypeError:
        yield x
        return
    if isinstance(x, (str, bytes)):
        yield x
        return
    for elem in it:
        yield from flatten(elem)

这篇关于将变量指定为列表而不在函数中覆盖它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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