Reputation: 179
Let's say I have a list of tuples
l = [('A', 12345), ('A', 2435), ('A', 2342), ('B', 2968), ('B', 9483), ('C', 563)]
What is the most efficient way to make the items in my list unique, like this:
l = [('A.1', 12345), ('A.2', 2435), ('A.3', 2342), ('B.1', 2968), ('B.2', 9483), ('C.1', 563)]
Upvotes: 3
Views: 93
Reputation: 7204
By request, i've posted a pandas approach to this question:
import pandas as pd
df = pd.DataFrame(l)
# Create a count per group and add them to the string:
df[0] = df[0] + "." + list(map(str,list(df.groupby(0).cumcount()+1)))
# Transpose the columns to rows so we can aggregate by 2 and create a tuple:
df.T.groupby(np.arange(len(df.T))//2).agg(tuple).to_numpy().tolist()[0]
Output
[('A.1', 12345),
('A.2', 2435),
('A.3', 2342),
('B.1', 2968),
('B.2', 9483),
('C.1', 563)]
Upvotes: 3
Reputation: 26315
You could also group with a collections.defaultdict()
, then flatten the result with itertools.chain.from_iterable()
. This works whether the result is sorted or not.
from collections import defaultdict
from itertools import chain
l = [("A", 12345), ("A", 2435), ("A", 2342), ("B", 2968), ("B", 9483), ("C", 563)]
# First group by first item in tuple
groups = defaultdict(list)
for k, v in l:
groups[k].append(v)
# defaultdict(<class 'list'>, {'A': [12345, 2435, 2342], 'B': [2968, 9483], 'C': [563]})
# Now flatten grouped items into a flat list
result = list(
chain.from_iterable(
(("%s.%d" % (k, i), e) for i, e in enumerate(v, start=1))
for k, v in groups.items()
)
)
print(result)
Output:
[('A.1', 12345), ('A.2', 2435), ('A.3', 2342), ('B.1', 2968), ('B.2', 9483), ('C.1', 563)]
Upvotes: 2
Reputation: 473763
One approach could be to group with itertools.groupby()
and then "expand" the groups:
from itertools import groupby
from operator import itemgetter
l = [('A', 12345), ('A', 2435), ('A', 2342), ('B', 2968), ('B', 9483), ('C', 563)]
print([
(f'{k}.{index}', v)
for k, g in groupby(l, itemgetter(0))
for index, (_, v) in enumerate(g, start=1)
])
Prints:
[('A.1', 12345), ('A.2', 2435), ('A.3', 2342), ('B.1', 2968), ('B.2', 9483), ('C.1', 563)]
Note that for the grouping to work, the input l
needed to be ordered by the grouping key which it seems is the case for this example input.
Upvotes: 4