Getting at an item in a list of tupples

Fernando Pérez fperez528 at yahoo.com
Mon Dec 10 13:02:52 EST 2001


Bob Greschke wrote:

> Here's what I've got
> 
>    a = []
>    a.append((ints, floats, strings))
>    a.append((ints, floats, strings))
>    a.append((ints, floats, strings))
>    a.append((ints, floats, strings))
>    ...
> 
> I want to do something like
> 
>    print max(of all of the floats)
>    print min(of all of the floats)
> 
> In general, how do you get at the floats (or ints, or strings)?  We
> can see doing something with map() calling a function that returns the
> second item, but isn't there something a little simpler?

Sorry, but I just fail to see what is 'not simple' about:

In [1]: a = []
In [2]: a.append((3,4.5,'hi'))
In [3]: a.append((0,8.5,'spam'))
In [4]: a.append((9,-5.3,'eggs'))
In [5]: a
Out[5]=
[(3, 4.5, 'hi'), (0, 8.5, 'spam'), (9, -5.2999999999999998, 'eggs')]

# now get your floats:
In [6]: max(map(lambda x:x[1],a))
Out[6]= 8.5

# or your ints:
In [7]: max(map(lambda x:x[0],a))
Out[7]= 9

Honestly, I don't see how to do 'simpler' than this, but I'd love to learn of 
a simpler way if someone has one.

Cheers,

f



More information about the Python-list mailing list