Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python : How to refer itself in the list comprehension? [duplicate]

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]?

ADD

Sorry, my explain is bad...

I want to get the list by a high-speed way.

input list

list_a = [0,0,1,0,0,0,1,0,0,1,0]

output list

list_c = [0, 0, 1, 0.9, 0.8, 0.7, 1, 0.9, 0.8, 1, 0.9]

like a saw tooth list.

like image 790
Hiroyuki Taniichi Avatar asked Jan 11 '18 10:01

Hiroyuki Taniichi


People also ask

Does list comprehension create a copy?

Using list comprehension. The method of list comprehension can be used to copy all the elements individually from one list to another.

CAN YOU HAVE else in list comprehension Python?

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.

Why are list comprehensions fast?

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.


3 Answers

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])
like image 116
Andrea Corbellini Avatar answered Oct 09 '22 15:10

Andrea Corbellini


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))
like image 39
user2390182 Avatar answered Oct 09 '22 15:10

user2390182


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)]
like image 43
zipa Avatar answered Oct 09 '22 16:10

zipa