[Tutor] Testing Membership in a Sequence
Karl Pflästerer
sigurd at 12move.de
Tue Mar 16 10:41:43 EST 2004
Christian Wyglendowski <- Christian.Wyglendowski at greenville.edu wrote:
> What I am actually trying to do is look for command line options in
> sys.argv.
> if '-o' in sys.argv or '--option' in sys.argv:
> apply_option()
You could either use the optparse module or subclass the list class and
define a custom __contains__ method.
class MList (list):
def __contains__(self, seq):
try:
for e in seq:
if list.__contains__(self, e): return True
return False
except TypeError:
return list.__contains__(self, seq)
For two options it may be a bit overkill but for a larger list it can be
convenient.
Here's an example:
In [42]: lst = MList(range(10))
In [43]: lst
Out[43]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [44]: 3 in lst
Out[44]: True
In [45]: (3, 11, 9) in lst
Out[45]: True
In [46]: (11, 20, -1) in lst
Out[46]: False
So you could write:
if ('-o', '--option) in MList(sys.argv): ...
Karl
--
Please do *not* send copies of replies to me.
I read the list
More information about the Tutor
mailing list