list to table

Jon Clements joncle at googlemail.com
Thu Nov 5 11:57:23 EST 2009


On Nov 5, 4:09 pm, "Alf P. Steinbach" <al... at start.no> wrote:
> * jay:
>
>
>
>
>
> > I have a long list of data of associations between values with a value
> > to that association as follows..
>
> > (var) to (var) = (var) hits
> > A B 1
> > B A 1
> > A B 3
> > B A 3
> > A C 7
> > C A 2
>
> > And need to build a table as follows that accumulates the above:
>
> > row is (from)
> > column is (to)
>
> >    A B C
> > A 0 4 7
> > B 4 0 0
> > C 2 0 0
>
> > Just can't seam to figure out how to manage this programatically.
>
> You're not very clear on what A, B and C are. Assuming that they're constants
> that denote unique values you can do something like
>
> <code>
> table = dict()
> for k1, k2, n in list:
>      position = (k1, k2)
>      if position not in table:
>          table[position] = n
>      else:
>          table[position] += n
> </code>
>
> Disclaimer: I'm a Python newbie so there may be some much easier way...
>
> Cheers & hth.,
>
> - Alf

I read the OP as homework (I'm thinking Scott did as well), however,
your code would be much nicer re-written using collections.defaultdict
(int)... which I don't think is giving anything away...

However, the challenge of making it 'tabular' or whatever the
requirement of 'table' is, is still there.

Jon.




More information about the Python-list mailing list