简体   繁体   English

List Comprehension重置迭代器变量?

[英]List Comprehension reset the iterator variable?

Is it possible to reset x in 是否可以重置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. 或改为使用一些while循环。 The thing is I'd like to run this comprehension list on my lis once I'm done, and not just one iteration. 事情是,我想在完成后在lis上运行此理解列表,而不仅仅是一次迭代。

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. 然后在第一个达到零时停止。

You could cycle the list until you hit your condition, here we break on the first value hitting 0 : 您可以cycle列表,直到遇到问题为止,在这里我们打破第一个达到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]

Say you want to decrease all members of the list by 1 until the smaller member(s) achieve value of 0. 假设您要将列表中的所有成员减少1,直到较小的成员的值为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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM