Better way to do this?
pavlovevidence at gmail.com
Mon Feb 11 23:37:25 CET 2008
On Feb 11, 3:57 pm, imho <ce... at comeno.it> wrote:
> PRC ha scritto:
> > 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 ]
> > 'dog'
> > It does the job, I was just curious if there was a better way to do
> > it.
A listcomp will traverse the whole tuple even if it finds the code
early in the tuple. It's better just use a for loop and break out as
soon as you find it.
for code,pet in pets:
if value == code:
raise ValueError("code %s not found" % value)
As an added bonus, you get a more useful error message if it's not
there (I know what you said, but bugs happen). If it's too bulky for
you, put it into its own function and call it.
> Can't You first convert the tuple of tuples in a dict, and then
> retrieving the value given a code value ?
> >>> dct = dict(pets)
> >>> dct
A linear search might be faster than building a dict if this search is
only to be done once for a given tuple.
More information about the Python-list