lsit_a = [2, 4, 3, 6, 3, 8, 5]
list comprehension is very useful.
list_b = [a**2 for a in list_a]
I want to know how to write a self-reference in the python list comprehension.
for example -
list_c = [a**2 if i == 0 else a*2 + (itself[i-1]) for i, a in enumurate(list_a)]
how to write the part of itself[i-1]
?
Sorry, my explain is bad...
I want to get the list by a high-speed way.
list_a = [0,0,1,0,0,0,1,0,0,1,0]
list_c = [0, 0, 1, 0.9, 0.8, 0.7, 1, 0.9, 0.8, 1, 0.9]
like a saw tooth list.
Using list comprehension. The method of list comprehension can be used to copy all the elements individually from one list to another.
Python list comprehension with if-else. Here, we can see list comprehension with if else in Python. In this example, I have a variable as fruits and the if-else condition is used as i%3==0, if the condition is true then the result will be mango else orange.
List comprehensions are faster than for loops to create lists. But, this is because we are creating a list by appending new elements to it at each iteration.
List comprehension is meant to be a compact expression for the most straightforward use cases. You cannot reference the list itself in list comprehension, for that just use a regular for-loop:
list_c = []
for i, a in enumerate(list_a):
if i == 0:
list_c.append(a ** 2)
else:
list_c.append(a * 2 + list_c[i-1])
You can also rewrite that loop in a more efficient way:
list_a_iterator = iter(list_a)
list_c = [next(list_a_iterator) ** 2] # May raise StopIteration if list_a is empty
for item in list_a_iterator:
list_c.append(item * 2 + list_c[-1])
You cannot reference a list before it is created. However, you can use this hacky reduce
approach if you desperately want a one-liner:
list_c = reduce(lambda lst, a: lst + [lst[-1] + a**2], list_a, [0])[1:]
And in Python > 3.2, you can use itertools.accumulate
:
from itertools import accumulate
list_c = list(accumulate(a**2 for a in list_a))
You can access list_a
from your comprehension:
[a**2 if i == 0 else a*2 + list_a[i-1]**2 if i == 1 else a*2 + list_a[i-1]*2 for i, a in enumerate(list_a)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With