On Sun, Jan 23, 2011 at 1:05 PM, CM <cmpyt...@gmail.com> wrote:
> 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?

Assuming your conditions all involve membership testing...
Use the built-in any() and all() functions. For your first example:

wanteds = [A, B]
unwanteds = [C, D]
if all(wanted in your_list for wanted in wanteds) and \
    not any(unwanted in your_list for unwanted in unwanteds):
    do_whatever()

You could pull this out into a separate function if you wish.

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to