taylormade201
taylormade201

Reputation: 696

Group list elements into tuples by index

I have a list like [1,2,3,1,2,3,1,2,3] and I would like to group the common elements by their index so the result would be: [(0,3,6),(1,4,7),...]

Upvotes: 1

Views: 493

Answers (2)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250891

If order matters then use collections.OrderedDict otherwise go for collections.defaultdict:

>>> from collections import OrderedDict
>>> lis = [1,2,3,1,2,3,1,2,3]
>>> d = OrderedDict()
>>> for i, item in enumerate(lis):
    d.setdefault(item, []).append(i)
...     
>>> d.values()
[[0, 3, 6], [1, 4, 7], [2, 5, 8]]

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1121486

Use a dictionary; collections.defaultdict() would be easiest:

from collections import defaultdict

indices = defaultdict(list)
for index, value in enumerate(inputlist):
    indices[value].append(index)

result = [tuple(indices[value]) for value in sorted(indices)]

This assumes that you wanted the indices ordered by value sort order.

Upvotes: 2

Related Questions