有没有办法在python中的列表推导中使用两个if条件

Shi*_*dla 20 python list

假设我有一个清单

my_list = ['91 9925479326','18002561245','All the best','good']
Run Code Online (Sandbox Code Playgroud)

现在我想忽略在列表中的字符串开始91和18 像下面

result = []
for i in my_list:
   if not '91' in i:
      if not '18' in i:
         result.append(i) 
Run Code Online (Sandbox Code Playgroud)

所以在这里我想通过列表推导来实现这一点.

无论如何,如果条件列表中的条件,写两个?

Dan*_*man 25

[i for i in my_list if '91' not in i and '18' not in i]
Run Code Online (Sandbox Code Playgroud)

请注意,您不应将其list用作变量名称,它会影响内置函数.


Igo*_*bin 10

如果您有两个以上的值(91和18)或它们是动态生成的,那么最好使用这种结构:

[i for i in my_list if not i.startswith(('91', '18'))]
Run Code Online (Sandbox Code Playgroud)

或者,如果你想检查91和18在字符串(不仅在开头),使用in代替startswith:

[i for i in my_list if all(x not in i for x in ['91', '18'])]
Run Code Online (Sandbox Code Playgroud)

用法示例:

>>> my_list = ['91 9925479326','18002561245','All the best','good']
>>> [i for i in my_list if all(not i.startswith(x) for x in ['91', '18'])]
['All the best', 'good']
>>> 
Run Code Online (Sandbox Code Playgroud)