Jim
Jim

Reputation: 1357

python group items in tuple with no duplicates

I have

(('A', '1', 'UTC\xb100:00'), ('B', '1', 'UTC+01:00'), ('C', '1', 'UTC+02:00'), ('D', '1', 'UTC+01:00'), ('E', '1', 'UTC\xb100:00'), ('F', '1', 'UTC+03:00'))

And would like

  (('A','E, '1', 'UTC\xb100:00'), ('B','D', '1', 'UTC+01:00'), ('C', '1', 'UTC+02:00'), ('F', '1', 'UTC+03:00'))

I've seen you can do this with a list, but I've not seen this done using a turple.. Is this possible..?

Upvotes: 1

Views: 474

Answers (5)

miku
miku

Reputation: 188034

It might be overkill to use pandas for this, but you could:

import pandas as pd

# somehow, pandas 0.12.0 does prefers 
# a list of tuples rather than a tuple of tuples
t = [('A', '1', 'UTC\xb100:00'), 
     ('B', '1', 'UTC+01:00'), 
     ('C', '1', 'UTC+02:00'), 
     ('D', '1', 'UTC+01:00'), 
     ('E', '1', 'UTC\xb100:00'), 
     ('F', '1', 'UTC+03:00')]

df = pd.DataFrame(t, columns=('letter', 'digit', 'tz'))
grouped = df.groupby('tz')

print(grouped.groups)

# {'UTC+01:00': [1, 3],
#  'UTC+02:00': [2],
#  'UTC+03:00': [5],
#  'UTC\xb100:00': [0, 4]}

merged = []
for key, vals in grouped.groups.iteritems():
    update = [ t[idx][0] for idx in vals ] # add the letters
    update += t[idx][1:] # add the digit and the TZ
    merged.append(update)

print(merged)
# [['F', '1', 'UTC+03:00'], ['C', '1', 'UTC+02:00'], \
#  ['A', 'E', '1', 'UTC\xb100:00'], ['B', 'D', '1', 'UTC+01:00']]

The upside is a rather concise df.groupby('tz'), the downside a rather heavy dependency (pandas plus its dependencies).

One can condense the merge into one a bit less comprehensible line:

merged = [[t[idx][0] for idx in vs] + list(t[idx][1:])
            for vs in grouped.groups.values()]

Upvotes: 0

smac89
smac89

Reputation: 43108

If you just care that the items with the same code are in the same tuple, then this answer works:

nodup = {}
my_group_of_items = (('A', '1', 'UTC\xb100:00'), ('B', '1', 'UTC+01:00'), ('C', '1', 'UTC+02:00'), ('D', '1', 'UTC+01:00'), ('E', '1', 'UTC\xb100:00'), ('F', '1', 'UTC+03:00'))
for r in my_group_of_items:
    if r[-1] not in nodup: nodup[r[-1]] = set()
    nodup[r[-1]] |= set(r[:-1])

result = [ tuple(list(nodup[t])+[t]) for t in nodup ]
print result

Upvotes: 0

zs2020
zs2020

Reputation: 54524

You can use comprehension, but still a bit complex.

tuples = (('A', '1', 'UTC\xb100:00'), ('B', '1', 'UTC+01:00'), ('C', '1', 'UTC+02:00'), ('D', '1', 'UTC+01:00'), ('E', '1', 'UTC\xb100:00'), ('F', '1', 'UTC+03:00'))

>>values = set(map(lambda x:x[1:3], tuples))
set([('1', 'UTC+03:00'), ('1', 'UTC\xb100:00'), ('1', 'UTC+01:00'), ('1', 'UTC+02:00')])

>>f = [[y[0] for y in tuples if y[1:3]==x] for x in values]
[['F'], ['A', 'E'], ['B', 'D'], ['C']]

>>r = zip((tuple(t) for t in f), values)
[(('F',), ('1', 'UTC+03:00')), (('A', 'E'), ('1', 'UTC\xb100:00')), (('B', 'D'), ('1', 'UTC+01:00')), (('C',), ('1', 'UTC+02:00'))]

>>result = tuple([sum(e, ()) for e in r])
(('F', '1', 'UTC+03:00'), ('A', 'E', '1', 'UTC\xb100:00'), ('B', 'D', '1', 'UTC+01:00'), ('C', '1', 'UTC+02:00'))

To put it together:

values = set(map(lambda x:x[1:3], tuples))
f = [[y[0] for y in tuples if y[1:3]==x] for x in values]
r = zip((tuple(t) for t in f), values)
result = tuple([sum(e, ()) for e in r])

Upvotes: 0

6502
6502

Reputation: 114481

With tuples you're not allowed to modify the content, but you can for example concatenate tuples to get other tuples.

def process(data):
    res = []
    for L in sorted(data, key=lambda x:x[2][-5:]):
        if res and res[-1][2][-5:] == L[2][-5:]:
            # Same group... do the merge
            res[-1] = res[-1][:-2] + (L[0],) + res[-1][-2:]
        else:
            # Different group
            res.append(L)
    return res

The end result seems to me is more a list (logically homogeneous content) rather than a tuple, but if you really need a tuple you can just return tuple(res) instead.

Upvotes: 0

alecxe
alecxe

Reputation: 473873

You can make use of groupby, but you need to sort the input first, like this:

from itertools import groupby
from operator import itemgetter

l = (('A', '1', 'UTC\xb100:00'), ('B', '1', 'UTC+01:00'), ('C', '1', 'UTC+02:00'), ('D', '1', 'UTC+01:00'), ('E', '1', 'UTC\xb100:00'), ('F', '1', 'UTC+03:00'))

result = []
key_items = itemgetter(1, 2)
for key, group in groupby(sorted(l, key=key_items), key=key_items):
    item = []
    item.extend([k[0] for k in group])
    item.extend(key)
    result.append(tuple(item))

print tuple(result)

This code prints:

(('B', 'D', '1', 'UTC+01:00'), ('C', '1', 'UTC+02:00'), ('F', '1', 'UTC+03:00'), ('A', 'E', '1', 'UTC\xb100:00'))

It's not that beautiful, I understand.

Upvotes: 1

Related Questions