循环python的两个条件

循环python的两个条件,python,loops,if-statement,Python,Loops,If Statement,我有如下数据 lst = ['abs', '@abs', '&abs'] 我需要用@或&更换所有零件。我确实喜欢这个 new = [] simbol1 = '@' simbol2 = '&' for item in lst: if simbol1 not in item: if simbol2 not in item: new.append(item) lst = ['abs', '@abs', '&abs'] new

我有如下数据

lst = ['abs', '@abs', '&abs']
我需要用
@
&
更换所有零件。我确实喜欢这个

new = []
simbol1 = '@'
simbol2 = '&'
for item in lst:
    if simbol1 not in item:
        if simbol2 not in item:
            new.append(item)
lst = ['abs', '@abs', '&abs']
new = []
simbol1 = '@'
simbol2 = '&'
for item in lst:
    if any([simbol1 not in item , simbol2 not in item]):
        new.append(item)
但是有没有更简单的方法来实现这个循环呢? 我试过这样做

new = []
simbol1 = '@'
simbol2 = '&'
for item in lst:
    if simbol1 not in item:
        if simbol2 not in item:
            new.append(item)
lst = ['abs', '@abs', '&abs']
new = []
simbol1 = '@'
simbol2 = '&'
for item in lst:
    if any([simbol1 not in item , simbol2 not in item]):
        new.append(item)
但我明白了

new
['abs', '@abs', '&abs']

在这种情况下,使用多个条件的正确方法是什么?

如果s:

if simbol1 not in item and simbol2 not in item:
    new.append(item)

您可以使用
列表理解
&合并两个
,如果
,如下所示:

>>> lst = ['abs', '@abs', '&abs']
>>> new_lst = [l for l in lst if '@' not in l and '&' not in l]
>>> new_lst
['abs']
>>> 

如果出现以下情况,也可以使用
all()
代替多个

>>> lst = ['abs', '@abs', '&abs']
>>> new_lst = [l for l in lst if all(x not in l for x in ['@','&'])]
>>> new_lst
['abs']
>>> 
,你可以

new_list = list(filter(lambda x: all(f not in x for f in ['@', '&']), lst))

作为说明,
lambda
函数通过
过滤出所有计算结果为
False
的值,确保禁止的
f
字符均不在字符串中
filter
返回一个生成器,这样就可以创建一个
列表

您的代码非常接近正确;唯一的问题是你把否定倒转了

lst = ['abs', '@abs', '&abs']
out_lst = [el for el in lst if '@' not in el and '&' not in el]
print(out_lst) # ['abc']
这:

…是在问“这些东西中有没有一个不在项目中?”就像在英语中一样,如果一个不在项目中,但另一个在项目中,这是正确的,这不是你想要的。只有当项目中没有任何一项时,您才希望它为真

换句话说,您需要“所有这些都不在项目中吗?”

…或“这些都不在项目中吗?”


但是,当您只有一个固定的两件事情列表时,通常更容易使用
而不是
任何
所有
——就像在英语中一样:

if symbol1 not in item and simbol2 not in item:
…或:

if not (simbol1 in item or simbol2 in item):
另一方面,如果您有一大堆符号要检查,或者有一个直到运行时才知道的符号列表,那么您可能需要一个循环:

if all(simbol not in item for simbol in (simbol1, simbol2)):

if not any(simbol in item for simbol in (simbol1, simbol2)):

你需要用全部替换任何。
if not (simbol1 in item or simbol2 in item):
if all(simbol not in item for simbol in (simbol1, simbol2)):

if not any(simbol in item for simbol in (simbol1, simbol2)):