将列表添加到列表中,然后将另一个列表添加到刚添加的列表中

时间:2019-11-12 18:42:50

标签: python list

基本上,我正在尝试通过使用lambda函数并将其辅助到列表来对int进行编码。

当前实施:

succ = (lambda f: lambda n: f(n))

def encode(i):
    zeroList = []
    secondaryList = []
    encodedList = [succ]

    if i == 0:
        return zeroList  
    else:
        x = i - 1
        for x in range(0, x):
            secondaryList.append(succ)
        encodedList.append(secondaryList)
    return encodedList

因此,encode(4)的输出当前为:

[<function <lambda> at 0x0000024D71943DC8>, [<function <lambda> at 0x0000024D71943DC8>, <function <lambda> at 0x0000024D71943DC8>, <function <lambda> at 0x0000024D71943DC8>]]

当我想要它时:

[fun, [fun, [fun, [fun, fun]]]]

所以我会继续在当前列表中添加一个列表,如果有道理。

1 个答案:

答案 0 :(得分:0)

尝试使用[fun, [fun, [fun, [fun, fun]]]]输出类型:

succ = (lambda f: lambda n: f(n))
def encode(i):
    return [succ] + [encode(i-1)] if i>0 else succ
print(encode(4))

输出

[<function <lambda> at 0x7fb72267d710>, [<function <lambda> at 0x7fb72267d710>, [<function <lambda> at 0x7fb72267d710>, [<function <lambda> at 0x7fb72267d710>, <function <lambda> at 0x7fb72267d710>]]]]

尝试使用[fun, [fun, [fun, [fun]]]]输出类型:

def encode(i):
    return [succ] + [encode(i-1)] if i>1 else [succ]
print(encode(4))

输出

[<function <lambda> at 0x7fb72267d710>, [<function <lambda> at 0x7fb72267d710>, [<function <lambda> at 0x7fb72267d710>, [<function <lambda> at 0x7fb72267d710>]]]]