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: Peter Otten <__peter__@web.de>
Date: Tue Jul 12 2005 - 06:48:40 CEST

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".
>
> I know I can do [elem for elem in lst if elem[3] == x][0] or (elem for
> elem in lst if elem[2] == y).next() but it feels kinda ugly; is there a
> better way?
>
> (something like lst.index(x, key=..) or lst.find(y, key=..) would be
> nice)

>>> 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
>>> items.index(Key(lambda x: x[1] == "c"))
2

A cleaner and probably faster solution would be to subclass list and
override index()/find().

Peter
Received on Thu Sep 29 16:53:34 2005