你好,我有一个包含真假值的列表,
visited =[True, False, True, False]
我不确定它是否可能,但我喜欢在列表为空或访问的列表没有更多假值时在 while 循环中使用列表逻辑我喜欢结束 While 循环 这是我的尝试,它似乎是一个无限循环。当我遇到一个错误值时,我无法更改错误值,这是我的代码
class mass:
def __init__(self):
visited =[True, False, True, False]
self.x = 0
while len([self.x for self.x, values in enumerate(visited) if visited[self.x] == False ]) > 0:
print(self.x)
visited[self.x] = True
print(visited)
self.x = 0
c = mass()
c
我想更改假值并在 while 循环中当长度达到 0 时停止循环。当我在 python 控制台中执行此操作时,我得到了输出
>>> [x for x, values in enumerate(visited) if visited[x] == False ]
[1, 3]
visited =[True, True, True, True]
如果我这样做
>>> visited =[True, True, True, True]
>>> [x for x, values in enumerate(visited) if visited[x] == False ]
[]
然后我试了一下
>>> print(len([x for x, values in enumerate(visited) if visited[x] == False ]))
0
这让我觉得我能做到
while len([x for x, values in enumerate(visited) if visited[x] == False ]) > 0
不断循环。 任何建议都会很好,谢谢
最佳答案
在你在评论中澄清之后:
考虑这个例子:
import random
li = [False, False, False]
while not all(li):
print('here')
i = random.randint(0, 2)
li[i] = True
此代码将打印 'here' 任意次数,直到 li
的所有值都变为 True
。
这个答案的关键是while
循环的条件,while not all(li)
。
关于python - 在 while 循环中列出逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37326164/