有什么办法可以使这小段代码更短? (蟒蛇)

时间:2018-07-26 01:46:25

标签: python coding-efficiency

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 __'等长链。 干杯

5 个答案:

答案 0 :(得分:2)

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]):
   ...

答案 1 :(得分:1)

您可以串联/合并所有列表并检查真实性:

while not all(first+second+third+fourth):

这将检查任何False-y值,如果为0,则返回True。

答案 2 :(得分:1)

while 0 in first + second + third + fourth:
    # do stuff

答案 3 :(得分:0)

您也可以map

ls = [first, second, third, fourth]
func = lambda x: 0 in x

while all(map(func, ls)):
    #dostuff

如果要使用all,请使用0 in first and 0 in second and ...。如果需要any0 in first等,请使用0 in second

答案 4 :(得分:0)

while not any(map(all, [first, second, ...])):