python - 创建与其自身部分的列表的最有效方法是什么?
问题描述
我想制作一个列表,例如下一个元素是基于前一个元素的值。这个解决方案没问题,但我想知道是否有更有效的方法来创建这个列表。
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]
解决方案
最有效的方法是使用 Python 内置函数:
lis = list(range(10, 0, -1))
碰巧,它也是最易读的。
但是,如果您坚持创建自己的递归函数,最好不要使用附加参数,而是将返回值与要添加的元素结合起来:
def addelement(stop):
if stop == 0:
return []
return [stop] + addelement(stop-1)
print(addelement(10))
推荐阅读
- python - 使用 Windows 资源管理器在文件上按 CTRL+C 后获取文件名
- python-3.x - Python3 - “ValueError:没有足够的值来解包(预期 3,得到 1)”
- jquery - jQuery比较中的通配符
- java - 当您需要将多种类型作为源传递时,实现 Spring 的 Converter 接口的最佳方式
- c++ - 仅使用加法/递归 C++ 对数字求平方
- c# - Microsoft.Extensions.Configuration 究竟如何依赖 ASP.NET Core?
- sql - 如何使用 groupby 和聚合函数将 SQL 查询中的行数返回为单个数字?
- python - while 循环没有读取变量
- python - Python:查找列表列表的范围
- vim - 使用当前文件类型的 ftplugin 文件打开缓冲区?