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. 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
.
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
:
>>> 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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.