[portland] Still Having List/Tuple Problems
Dylan Reinhardt
python at dylanreinhardt.com
Wed Apr 16 22:48:14 CEST 2008
Another approach to add to the pile:
>>> my_tuples = [('A',1),('A',2), ('A',3), ('A',4), ('B',1), ('B',2),
('B',3), ('B',4)]
>>> grouper = {}
>>> for left, right in my_tuples:
... grouper.setdefault(left, []).append(right)
...
now you have a dict with values groped by keys, as shown below...
>>> for key in grouper.keys():
... print key
... for value in grouper[key]:
... print '\t%s' % value
...
A
1
2
3
4
B
1
2
3
4
HTH,
Dylan
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