Searching through a list of tuples

Alan Green alan.green at gmail.com
Tue Jul 12 17:25:01 EDT 2005


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




More information about the Python-list mailing list