简体   繁体   English

递归列表填写 python

[英]Recursive list filling in python

Sometimes I need to fill lists recursively and to this point I have always done it like this (simple example, this should also work for complex recursive lists, eg exponential moving averages):有时我需要递归地填充列表,到目前为止,我总是这样做(简单的例子,这也适用于复杂的递归列表,例如指数移动平均线):

In [1]: def complex_func(a,b):
   ...:     return a + b
   ...: 
   ...: recursive_list = [1, 2]
   ...: for i in range(9):
   ...:     recursive_list.append(complex_func(
   ...:         recursive_list[-2],
   ...:         recursive_list[-1]
   ...:     ))
   ...: recursive_list
Out[1]: [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]

Is there a way to do this better?有没有办法更好地做到这一点? And with better I mean more pythonic or even faster.更好的意思是更多的pythonic甚至更快。 I have the feeling that this is not the best way.我感觉这不是最好的方法。

Maybe something like this (which is not working):也许是这样的(这是行不通的):

In [1]: recursive_list = [1, 2, complex_func(
   ...:         recursive_list[-2],
   ...:         recursive_list[-1]
   ...:     ) for i in range(9)]

You can use range .您可以使用range

start = 1
times = 9
res = list(range(start, start + times + 1))
print(res)

It's not clear why you need recursion.目前尚不清楚为什么需要递归。 You only refer to a single value at the end of the list, so you just need a variable to track that value.您只引用列表末尾的单个值,因此您只需要一个变量来跟踪该值。

seed = 1
my_list = []
for i in range(10):
    my_list.append(seed)
    seed = seed + 1

If you don't mind an external module, install more-itertools and use iterate :如果您不介意外部模块,请安装more-itertools并使用iterate

>>> from more_itertools import iterate
>>> from itertools import islice
>>> list(islice(iterate(lambda x: x + 1, 1), 10))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

For the Fibonacci numbers, use two seeds:对于斐波那契数,使用两个种子:

seed1 = 0  # my_list[-2]
seed2 = 1  # my_list[-1]
my_list = []
for i in range(10):
    my_list.append(seed1)
    seed1, seed2 = seed2, seed1 + seed2

You could use the extend method:您可以使用扩展方法:

def complex_func(a,b): return a+b

L = [1,2]
L.extend(complex_func(*L[-2:]) for _ in range(9))

print(L)
[1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]

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

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