Python oneline foreach verification in string

时间:2016-04-25 09:09:53

标签: python

I want to be sure that none item of a list is present on a string.

At the moment I do :

presents = False
for item in item_list:
    if item in string_control:
        presents = True
        break;

Is there a way to do it in only one line ? I really often do these types of control.

2 个答案:

答案 0 :(得分:2)

Yes :

presents = any(x in string_control for x in item_list)

答案 1 :(得分:1)

I think string_control has a value something like this. presents then becomes a boolean indicating the same as in your code but most likely in most circumstances you don't need the cast to bool. I.e. this probably works fine too: presents = [i for i in item_list if i == string_control]

string_control = None
presents = bool([i for i in item_list if i == string_control])