Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #110325 > unrolled thread

Re: Summary grid

Started byjmp <jeanmichel@sequans.com>
First post2016-06-22 18:20 +0200
Last post2016-06-22 18:20 +0200
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Summary grid jmp <jeanmichel@sequans.com> - 2016-06-22 18:20 +0200

#110325 — Re: Summary grid

Fromjmp <jeanmichel@sequans.com>
Date2016-06-22 18:20 +0200
SubjectRe: Summary grid
Message-ID<mailman.44.1466612453.11516.python-list@python.org>
On 06/22/2016 04:46 PM, Jignesh Sutar wrote:
> Say I have list of data as given in the example code below, I want to find
> all the unique categories (alphabetic letters) and unique IDs (numbers) and
> then produce a summary grid as manually entered in the "results". How could
> I code this?
>
> Many thanks in advance,
> Jignesh
>
>
> data= ["A.1", "A.2", "A.3", "B.1", "C.2", "C.3",  "D.4", "E.5", "E.6"]
>
> cols=[]
> rows=[]
> for item in data:
>      i=item.split(".")
>      if i[0] not in cols: cols.append(i[0])
>      if i[1] not in rows: rows.append(i[1])
>
> print cols
> print rows
>
> results=
> [["Row/Col", "A", "B", "C", "D", "E"],
> [1, 1, 1, 0, 0, 0],
> [2, 1, 0, 1, 0, 0],
> [3, 1, 0, 1, 0, 0],
> [4, 0, 0, 0, 1, 0],
> [5, 0, 0, 0, 0, 1],
> [6, 0, 0, 0, 0, 1]]
>

Easily done using only builtins and list comprehension:

data= ["A.1", "A.2", "A.3", "B.1", "C.2", "C.3",  "D.4", "E.5", "E.6"]
# python magic with the "zip" function
# "set" will take care of removing duplicates
categories, ids = map(set, zip(*[d.split('.') for d in data]))

results = []
for id_ in sorted(map(int,ids)):
     results.append([data.count("%s.%d" % (cat, id_)) for cat in 
sorted(categories)])

print results



If you don't really understand the zip function:
http://nedbatchelder.com/text/iter.html
The whole presentation is worth reading.

Cheers,

Jm

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web