Pythonic way of saying 'at least one of a, b, or c is in some_list'

HEK elkarouh at gmail.com
Fri Oct 29 04:15:17 EDT 2010


On Oct 28, 6:16 pm, "cbr... at cbrownsystems.com"
<cbr... 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
>
> Is there a better pythonic idiom for this situation?
>
> Cheers - Chas

The most pythonic way is the following:

class anyof(set):
	def __contains__(self,item):
		if isinstance(item,anyof):
			for it in item:
				if self.__contains__(it):
					return True
			else:
				return False
		return super(anyof,self).__contains__(item)

daysoff=anyof(['Saterday','Sunday'])
assert anyof(['monday','tuesday']) in daysoff

best regards
Hassan



More information about the Python-list mailing list