[portland] Still Having List/Tuple Problems
kirby urner
kirby.urner at gmail.com
Wed Apr 16 21:13:39 CEST 2008
You could use list comprensions:
>>> mydata
[('A', 1), ('A', 2), ('A', 8), ('B', 1), ('B', 2), ('B', 8), ('C', 1),
('C', 2), ('C', 8)]
>>> astuff = [j for (i,j) in mydata if i == 'A']
>>> astuff
[1, 2, 8]
>>> bstuff = [j for (i,j) in mydata if i == 'B']
>>> bstuff
[1, 2, 8]
If you don't know what all the keys are gonna
be you could build a list of unique ones:
>>> thekeys = set([i for (i,j) in mydata])
>>> thekeys
set(['A', 'C', 'B'])
>>> for thekey in thekeys:
print thekey
print [j for (i,j) in mydata if i == thekey]
A
[1, 2, 8]
C
[1, 2, 8]
B
[1, 2, 8]
Note there's no presumption the As, Bs are clumped together.
Kirby
On Wed, Apr 16, 2008 at 11:48 AM, Rich Shepard <rshepard at appl-ecosys.com> wrote:
> I have a mental block on understanding just how to index a list of tuples
> so I can extract the data in an orderly fashion.
>
> The list looks like this: [(A,1),(A,2), ... (A,8),(B,1),(B,2), ...
> (B,8),(C,1),(C2), ... (C,8)]
>
> What I want to do is extract all tuples grouped by the first element, then
> list the associated second elements). That is,
> A
> 1
> 2
> ...
> 8
>
> B
> 1
> 2
> ...
> 8
> etc.
>
> Referencing list[0] returns the first tuple; list[0][0] returns the first
> item in the first tuple; but I cannot cycle through the three first items
> extracting the second items associated with each.
>
> I've looked at my books and previous threads here, but I'm just not
> getting how this is done. I've played with list comprehensions, zip, and
> other tools without getting the proper syntax or results I need. Don't know
> why the answer keeps eluding me, but it does.
>
> Rich
>
> --
> Richard B. Shepard, Ph.D. | Integrity Credibility
> Applied Ecosystem Services, Inc. | Innovation
> <http://www.appl-ecosys.com> Voice: 503-667-4517 Fax: 503-667-8863
> _______________________________________________
> Portland mailing list
> Portland at python.org
> http://mail.python.org/mailman/listinfo/portland
>
More information about the Portland
mailing list