user764357
user764357

Reputation:

Access prior element in a list comprehension

I've looked around into list comprehensions on here, and can find a solution for this.

Closest I've come is questions that advice using enumerate() while iterating in a list comprehension.

What I'd like to do is access the prior element in a list comprehension. The context is this question on another StackExchange site.

Basically, if I get this string from stdin - 4,6,+2,+8, I'd like to output the array that is the integer of the number, or the number plus the value of the prior element. In the given case the final array is: 4,6,8,16 - or 4,6,6+2,(6+2)+8. Going from left to right with an array and for loop its trivial to generate, but I'm curious to know if it can be done in a single list comprehension.

As for what I have:

from sys import*
s=argv[1].split(',')
for i in range(len(s)):
 s[i]=eval(`s[i-1]`*(s[i][0]=='+')+s[i])
print s

Which prints the correct result, however the following list comprehension does not:

s=argv[1].split(',')
s=[eval(s[i-1]*(x[0]=='+')+x) for i,x in enumerate(s)]
print s

Which results in:

[4, 6, 8, 10]

Which is equivilient to 4, 6, +2+6, +2+8.

What I'd like to be able to do finally is something along the lines of:

s=[eval(PRIOR_VALUE*(x[0]=='+')+x) for x in argv[1].split(',')]

So can I easily access the prior computed element of a list comprehension in the same list comprehension?

Upvotes: 3

Views: 218

Answers (1)

user2357112
user2357112

Reputation: 280963

So can I easily access the prior computed element of a list comprehension in the same list comprehension?

Easily? No.

If you want to make things difficult for yourself, there are plenty of ways to save state information in a list comprehension. For example,

prev = [None]

s = [prev.__setitem__(0, val) or val
     for item in list
     for val in [something(item, prev[0])]]

This is not a good idea.

Upvotes: 3

Related Questions