[portland] Still Having List/Tuple Problems
kirby urner
kirby.urner at gmail.com
Thu Apr 17 01:49:05 CEST 2008
On Wed, Apr 16, 2008 at 4:24 PM, Rich Shepard <rshepard at appl-ecosys.com> wrote:
> On Wed, 16 Apr 2008, kirby urner wrote:
>
> >>>> thekeys = set([i for (i,j) in mydata])
>
> I thought this more elegant, but when I could not use the 'j' values
> associated with each 'i' value I did some reading on sets. They are
> iterable, but not indexable. And I need to access each 'j' associated with
> each 'i'.
>
Yeah, was just using the set to garner / harvest unique keys
(throwing away j values, keeping only i values), then in the
next loop building a data structure with filtration.
Here'd be a complete program, data set of my own invention:
IDLE 1.2.1
>>> thedata = [('salmon',1),('tuna',1),('salmon',3),('rockfish',4),('salmon',2),
('rockfish',2),('tuna',9),('barracuda',4),('trout',1),('barracuda',18)]
def groupstuff(anydata):
thekeys = set([i for (i,j) in anydata]) # get unique i values
grouped = {} # return a dictionary listing j values, indexed by i values
for key in thekeys:
grouped[key] = [ j for (i,j) in anydata if i == key ] # scoop out j values
return grouped
>>> groupstuff(thedata)
{'salmon': [1, 3, 2], 'tuna': [1, 9], 'barracuda': [4, 18],
'rockfish': [4, 2], 'trout': [1]}
def graphit(groups):
for key in groups.keys(): # loop through indexes
print key
for graph in sorted(groups[key]): # assume ordering of j-values matters
print graph
>>> graphit(groupstuff(thedata))
salmon
1
2
3
tuna
1
9
barracuda
4
18
rockfish
2
4
trout
1
> But, I learned quite a bit. I think the groupby() approach is most
> suitable for my need.
>
> Thanks all,
>
>
>
> Rich
More information about the Portland
mailing list