Better way to do this?

Diez B. Roggisch deets at nospam.web.de
Mon Feb 11 15:26:09 EST 2008


PRC schrieb:
> Hi folks,
> 
> I have a tuple of tuples, in the form--> ((code1, 'string1'),(code2,
> 'string2'),(code3, 'string3'),)
> 
> Codes are unique. A dict would probably be the best approach but this
> is beyond my control.
> 
> Here is an example:
>>>> pets = ((0,'cat'),(1,'dog'),(2,'mouse'))
> 
> If I am given a value for the code I need to retrieve the string
> representation. The value is guaranteed to be valid.
> 
> This is what I came up with...
> 
>>>> value=1
>>>> [ pet for code, pet in pets if value==code ][0]
> 'dog'
> 
> It does the job, I was just curious if there was a better way to do
> it.
> 

This is linear in the number of elements. It can get better (log_2 n) if 
you can rely on the order of codes as in your given example - then you 
should be able to use the module bisect to find the index quicker.

Diez



More information about the Python-list mailing list