Referencing Items in a List of Tuples
Bruno Desthuilliers
bdesth.quelquechose at free.quelquepart.fr
Sun Feb 25 16:25:34 EST 2007
rshepard at nospam.appl-ecosys.com a écrit :
> While working with lists of tuples is probably very common, none of my
> five Python books or a Google search tell me how to refer to specific items
> in each tuple.
t = "a", "b", "c"
assert t[0] == "a"
assert t[1] == "b"
assert t[2] == "c"
> I find references to sorting a list of tuples, but not
> extracting tuples based on their content.
loft = [(1, 2, 3), (1, 2, 4), (2, 3, 4)]
starting_with_one = [t for t in loft if t[0] == 1]
> In my case, I have a list of 9 tuples. Each tuple has 30 items. The first
> two items are 3-character strings, the remaining 28 itmes are floats.
>
> I want to create a new list from each tuple. But, I want the selection of
> tuples, and their assignment to the new list, to be based on the values of
> the first two items in each tuple.
>
> If I try, for example, writing:
>
> for item in mainlist:
> if mainlist[item][0] == 'eco' and mainlist[item][1] == 'con':
> ec.Append(mainlist[item][2:])
>
> python doesn't like a non-numeric index.
Hem... I'm afraid you don't understand Python's for loops. The above
should be:
ec = []
for item in mainlist:
if [item][0] == 'eco' and item[1] == 'con':
ec.append(item[2:])
which can also be written:
ec = [item[2:] for item in mainList \
if item[0] == 'eco' and item[1] == 'con']
> I would really appreciate a pointer so I can learn how to manipulate lists
> of tuples by referencing specific items in each tuple (string or float).
Did you actually tried reading some Python 101 material ?
More information about the Python-list
mailing list