A and B but not C in list

Christian Heimes lists at cheimes.de
Sun Jan 23 16:34:33 EST 2011


Am 23.01.2011 22:05, schrieb CM:
> In Python, is there a recommended way to write conditionals of the
> form:
> 
> "if A and B but not C or D in my list, do something."  ?
> 
> I may also have variations on this, like "if A but not B, C, or D".
> 
> Do I have to just write out all the if and elifs with all possible
> conditions, or is there a handier and more code-maintainable way to
> deal with this?

It's easier and faster if you convert the lists to sets first:

your_set = set(your_list)

if your_set.issuperset(set([A, B])) and your_set.isdisjoint(set([C, D])):
    ...

Christian




More information about the Python-list mailing list