Pythonic way of saying 'at least one of a, b, or c is in some_list'
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Fri Oct 29 05:43:48 EDT 2010
On Thu, 28 Oct 2010 09:16:42 -0700, cbrown at cbrownsystems.com wrote:
> It's clear but tedious to write:
>
> if 'monday" in days_off or "tuesday" in days_off:
> doSomething
>
> I currently am tending to write:
>
> if any([d for d in ['monday', 'tuesday'] if d in days_off]):
> doSomething
Use a simple generator expression and any.
if any(day in days_off for day in ['monday', 'tuesday']):
doSomething
You (partially) defeat the short-circuiting behaviour of any() by using a
list comprehension.
If you have a lot of items to test against, make days_off a set instead
of a list, which makes each `in` test O(1) instead of O(N). For small N,
the overhead of creating the set is probably going to be bigger than the
saving, so stick to a list.
Other than that, doing set operations is overkill -- it obfuscates the
intention of the code for very little gain, and possibly negative gain.
And as for the suggestion that you create a helper class to do the work,
that's surely the recommended way to do it in Java rather than Python.
--
Steven
More information about the Python-list
mailing list