有什么办法可以缩短这一小段代码吗? (Python)
Is there any way I can make this small piece of code shorter? (Python)
first = [0, 0, 0, 0]
second = [0, 0, 0, 0]
third = [0, 0, 0, 0]
fourth = [0, 0, 0, 0]
while 0 in first and 0 in second and 0 in third and 0 in fourth:
顶部的列表以每个值都为 0 开始。随着程序的进行,我计划将列表中的值从 0 更改为其他数字。实际上,我想知道是否有办法重写 'while' 语句来检查 0 是否在任何列表中,而不需要 'while not in __ and not in __' 等的长链。
干杯
while all(0 in i for i in [first,second,third,fourth]):
...
如果您想检查是否有任何列表包含 0,请执行以下操作:
while any(0 in i for i in [first,second,third,fourth]):
...
您可以concatenate/combine所有列表并检查真实性:
while not all(first+second+third+fourth):
这会检查是否有任何 False-y 值,returns如果有 0 则为真。
你也可以map
ls = [first, second, third, fourth]
func = lambda x: 0 in x
while all(map(func, ls)):
#dostuff
如果需要 0 in first and 0 in second and ...
,请使用 all
。如果你想要 0 in first
或 0 in second
等
,请使用 any
while not any(map(all, [first, second, ...])):
while 0 in first + second + third + fourth:
# do stuff
first = [0, 0, 0, 0]
second = [0, 0, 0, 0]
third = [0, 0, 0, 0]
fourth = [0, 0, 0, 0]
while 0 in first and 0 in second and 0 in third and 0 in fourth:
顶部的列表以每个值都为 0 开始。随着程序的进行,我计划将列表中的值从 0 更改为其他数字。实际上,我想知道是否有办法重写 'while' 语句来检查 0 是否在任何列表中,而不需要 'while not in __ and not in __' 等的长链。 干杯
while all(0 in i for i in [first,second,third,fourth]):
...
如果您想检查是否有任何列表包含 0,请执行以下操作:
while any(0 in i for i in [first,second,third,fourth]):
...
您可以concatenate/combine所有列表并检查真实性:
while not all(first+second+third+fourth):
这会检查是否有任何 False-y 值,returns如果有 0 则为真。
你也可以map
ls = [first, second, third, fourth]
func = lambda x: 0 in x
while all(map(func, ls)):
#dostuff
如果需要 0 in first and 0 in second and ...
,请使用 all
。如果你想要 0 in first
或 0 in second
等
any
while not any(map(all, [first, second, ...])):
while 0 in first + second + third + fourth:
# do stuff