Reputation: 7421
You can leave an element alone in a list comprehension according to a condition like this:
>>> mylist = [6,7,3,9,2,7,4]
>>> [x-1 if x!=7 else x for x in mylist]
[5, 7, 2, 8, 1, 7, 3]
What I need however is that the element is left alone if the element after it is 7.
[x-1 if next_element!=7 else x for x in mylist]
Desired output is:
[6,6,2,8,2,6,3]
I thought this might have been possible with enumerate and the index but can't work it out. Any ideas?
Upvotes: 1
Views: 4291
Reputation: 4629
Not a big fan of using one-liners when it becomes too complicated to read, but that works and the list is parsed only once:
mylist = [6,7,3,9,2,7,4]
L = len(mylist)
a = [x-1 if (i+1<N and mylist[i+1]!=7 or i==N-1) else x for i, x in enumerate(mylist)]
If you work with big lists and want to improve performance, you can do L = len(mylist)
outside of the list comprehension and replace it in the condition.
Upvotes: 1
Reputation: 2581
Sorry if this doesn't answer your question directly, but I find list comprehension should used in simple cases and avoid when the statement becomes overly complicated. See Googles styleguide for more detail.
I find the following much more readable.
mylist = [6,7,3,9,2,7,4]
newlist = []
length = len(mylist)
for index, item in enumerate(mylist):
if index + 1 < length and mylist[index + 1] == 7:
newlist.append(item)
else:
newlist.append(item - 1)
Upvotes: 1
Reputation: 13878
enumerate
and index
is one way, but you can do it with zip
:
mylist = [6,7,3,9,2,7,4]
[x[0]-(x[1]!=7) for x in zip(mylist, mylist[1:] + [0])]
# [6, 6, 2, 8, 2, 6, 3]
Upvotes: 7
Reputation: 61910
You could do:
mylist = [6, 7, 3, 9, 2, 7, 4]
result = [current - 1 if ne != 7 else current for current, ne in zip(mylist, mylist[1:])] + [mylist[-1] - 1]
print(result)
Output
[6, 6, 2, 8, 2, 6, 3]
Upvotes: 3