从列表中生成多个条件语句

generate multiple conditional statements from list

我有一个这样的列表

a = [1,0,6,9,6,0,6,0,1,4,0,7,5,0]

我想创建这样的条件语句:

if a[1,3,8,13] != 0:
    do something

而且这段代码显然是错误的。它必须是这样的:

if a[1] != 0 and a[3] != 0 and a[8] != 0 and a[13] != 0:
    do something

我想知道在我的例子中是否有更优雅的方法来使用 lambda 或循环编写多个条件语句。假设我的列表长度为 100,我需要为列表的 57 列创建条件语句。我可能不想以这种方式将它们全部写出来...... 谢谢

1.

您可以使用 all:

if all(a[i] != 0 for i in [1,3,8,13]): # => a[i] != 0 for every i 
    #do smth

或与any相同:

if not any(a[i] == 0 for i in [1,3,8,13]): # => there is no such i that a[i] == 0
    #do smth                               # => a[i] != 0 for every i 

2.

或者,您可以使用一些函数式编程的东西。
例如,您可以尝试 filter:

a = [1,0,6,9,6,0,6,0,1,4,0,7,5,0]
idxs_to_check = [1,3,8,13]

f = list(filter(lambda i: a[i] != 0, idxs_to_check))
if f == idxs_to_check:
    print('Meow')

或者,一行类似的条件:

if not list(filter(lambda i: a[i] == 0, [1,3,8,13])): 
    print('Meow')

3.

最后,在您的特定情况下,您可以使用包含零的列表的乘积为零的事实:

from numpy import prod

if prod([a[i] for i in [1,3,8,13]]):
    print("Woof")

你可以试试

a = [1,0,6,9,6,0,6,0,1,4,0,7,5,0]

if a[1] or a[2] or a[8] or a[13] != a[2]:
      print (“something”) #this part cuz I’m not sure what ur doing here

我真的不知道这是否有效,但愿它有效。 但这又可能会重复。所以你可能想要

if all(a[i] != 0 for i in [1,3,8,13]

基本上你遍历列表中你选择的每个位置以检查位置 0 是否相同

希望对您有所帮助!