繁体   English   中英

List Comprehension重置迭代器变量?

[英]List Comprehension reset the iterator variable?

是否可以重置x in

lis[3, 3, 4, 5]

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

或改为使用一些while循环。 事情是,我想在完成后在lis上运行此理解列表,而不仅仅是一次迭代。

说我想减少列表中的每个变量。

lis[3, 3, 4, 5]

lis[2, 2, 3, 4]

lis[1, 1, 2, 3]

lis[0, 0, 1, 2]

然后在第一个达到零时停止。

您可以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]

假设您要将列表中的所有成员减少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

让我们测试一下:

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