Re: Searching through a list of tuples
Available news archives: comp.lang.tcl - comp.lang.python - comp.security.firewalls - sci.crypt - comp.lang.php - comp.lang.javascript
Google
 
Web news.hping.org


comp.lang.python archive

Re: Searching through a list of tuples

From: Alan Green <alan.green@gmail.com>
Date: Tue Jul 12 2005 - 23:25:01 CEST

Peter Otten wrote:
> Repton wrote:
>
> > I often find myself storing data in a list of tuples, and I want to ask
> > questions like "what is the index of the first tuple whose 3rd element
> > is x", or "give me the first tuple whose 2nd element is y".

> >>> items = [(1, "a", 10), (2, "b", 20), (3, "c", 30)]
> >>> class Key(object):
> ... def __init__(self, key):
> ... self.key = key
> ... def __eq__(self, other):
> ... return self.key(other)
> ...
> >>> items.index(Key(lambda x: x[2] == 20))
> 1

Neat solution.

I'd add an extra kind of Key, since finding tuples where a given
position is equal to a given value seems to be the common case:

>>> class EqualKey(Key):
... def __init__(self, pos, val):
... super(EqualKey, self).__init__(lambda x: x[pos] == val)
...
>>> items.index(EqualKey(2, 20))
1

Alan
Received on Thu Sep 29 16:54:56 2005