JonCode
JonCode

Reputation: 241

List Comprehension reset the iterator variable?

Is it possible to reset x in

lis[3, 3, 4, 5]

test = [(tes(x)) for x in range (0, len(lis)) if lis[x] == "abc"]

or maybe instead use some while loop. The thing is I'd like to run this comprehension list on my lis once I'm done, and not just one iteration.

say that I want to decrement each variable in the list.

lis[3, 3, 4, 5]

lis[2, 2, 3, 4]

lis[1, 1, 2, 3]

lis[0, 0, 1, 2]

and then stop once the first hits zero.

Upvotes: 0

Views: 529

Answers (2)

LiMar
LiMar

Reputation: 2962

Say you want to decrease all members of the list by 1 until the smaller member(s) achieve value of 0.

def decrease_list(lis):
     def stop():
         raise Exception("Stop")
     try:
         while True:
             lis=[e - 1 if e>1 else stop() for e in lis]
     except:
         pass
     return lis

Let's test it:

In [35]: lis=[20, 12, 11, 10]

In [36]: decrease_list(lis)
Out[36]: [10, 2, 1, 0]

In [33]: lis =  [20, 12, 10, 10]

In [34]: decrease_list(lis)
Out[34]: [10, 2, 0, 0]

Upvotes: 1

Padraic Cunningham
Padraic Cunningham

Reputation: 180441

You could cycle the list until you hit your condition, here we break on the first value hitting 0:

from itertools import cycle

lis = [3, 3, 4, 5]
for ind, ele in enumerate(iter(lambda: next(cycle(lis)), 0)):
    lis[ind % len(lis)] -= 1

print(lis)
[0, 1, 2, 3]

Upvotes: 2

Related Questions