首页 > 解决方案 > 创建与其自身部分的列表的最有效方法是什么?

问题描述

我想制作一个列表,例如下一个元素是基于前一个元素的值。这个解决方案没问题,但我想知道是否有更有效的方法来创建这个列表。

def addelement(stop, x,y):
'''stop is to end the recursion, x is the list, y is the element being appended to x'''
    if stop == 0:
        return x
    x.append(y)
    return addelement(stop-1,x,y-1)

lis = addelement(10, [], 10)
print(lis)
# returns : [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

标签: pythonlistrecursionlist-comprehension

解决方案


最有效的方法是使用 Python 内置函数:

lis = list(range(10, 0, -1))

碰巧,它也是最易读的。

但是,如果您坚持创建自己的递归函数,最好不要使用附加参数,而是将返回值与要添加的元素结合起来:

def addelement(stop):
    if stop == 0:
        return []
    return [stop] + addelement(stop-1)

print(addelement(10))

推荐阅读