繁体   English   中英

两个条件循环python

[英]Two conditions loop python

我有如下数据

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
['abs', '@abs', '&abs']

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

您可以使用list comprehension并将两个if合并,如下所示:

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

您还可以使用all()代替多个if例如:

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

您可以将两个if组合在一起:

if simbol1 not in item and simbol2 not in item:
    new.append(item)
lst = ['abs', '@abs', '&abs']
new = []
simbol1 = '@'
simbol2 = '&'
for item in lst:
    if all([simbol1 not in item , simbol2 not in item]):
       new.append(item)
print (new)

Functionally ,您可以

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

作为说明, lambda函数通过filtering所有计算结果为False值,确保所有禁止使用的f字符都不在字符串中。 filter返回一个生成器,因此可以将其生成一个list

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

您的代码非常正确。 唯一的问题是您将否定取反。

这个:

if any([simbol1 not in item , simbol2 not in item]):

……在问“这些物品中是否有没有?” 就像英语一样,如果其中一个不在项目中,而另一个在项目中,那是正确的,这不是您想要的。 如果项目中都没有,则只希望它为true。

换句话说,您想要“是否所有这些都不在物料中?”

if all([simbol1 not in item, simbol2 not in item]):

……或“这些物品都不是吗?”

if not any([simbol1 in item, simbol2 in item]):

但是,当您只有两个这样的固定列表时,再次使用and / or代替anyall通常会更容易,就像英语一样:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM