tags:

views:

38

answers:

1

I joined two tables together and what I like to do is concatenate multi vaule in one records without duplicated value.

  1. Input Table

    Table name: TAXLOT_ZONE
    TID ZONE
    1 A
    1 A
    1 B
    1 C
    2 D
    2 D
    2 E
    3 A
    3 B
    4 C
    5 D

  2. Desirable output table looks like;

    table name: Taxlot_zone_out
    TID ZONE
    1 A, B, C
    2 D, E
    3 A, B
    4 C
    5 D

+1  A: 

Assuming your table is in sorted order and is iterable, you can use itertools.groupby to group rows with the same first element.

l = [(1, 'A'), (1, 'A'), (1, 'B'), (1, 'C'),
     (2, 'D'), (2, 'D'), (2, 'E'),
     (3, 'A'), (3, 'B'),
     (4, 'C'),
     (5, 'D')]

from itertools import groupby
from operator import itemgetter
result = [(taxlot, list(set(v for k,v in g)))
          for taxlot, g in groupby(l, itemgetter(0))]

Result:

[(1, ['A', 'C', 'B']),
 (2, ['E', 'D']),
 (3, ['A', 'B']),
 (4, ['C']),
 (5, ['D'])]
Mark Byers