2

Can You help me to convert Python list:

[(1, 'a'), (2, 'b'), (2, 'c'), (3, 'd'), (3, 'e')]

so that: (1, 'a') is index 0

(2, 'b'), (2, 'c') are both index 1

(3, 'd'), (3, 'e') are both index 2

Simply, all tuples which element[0] is equal, have same index.

Thank You,

2 Answers 2

6

itertools.groupby to the rescue!:

lst = [(1, 'a'), (2, 'b'), (2, 'c'), (3, 'd'), (3, 'e')]
lst.sort(key=lambda x: x[0])  #Only necessary if your list isn't sorted already.
new_lst = [list(v) for k,v in itertools.groupby(lst,key=lambda x:x[0])]

You could use operator.itemgetter(0) instead of the lambda if you wanted...

demo:

>>> import itertools
>>> lst = [(1, 'a'), (2, 'b'), (2, 'c'), (3, 'd'), (3, 'e')]
>>> lst.sort(key=lambda x: x[0])
>>> new_lst = [list(v) for k,v in itertools.groupby(lst,key=lambda x:x[0])]
>>> new_lst
[[(1, 'a')], [(2, 'b'), (2, 'c')], [(3, 'd'), (3, 'e')]]
Sign up to request clarification or add additional context in comments.

Comments

0

It's not clear what you want, but this will group the items into lists according ot their first element.

groups = collections.defaultdict(list)
for x,y in items:
    groups[x].append(y)

1 Comment

@Jon can't believe I missed that typo. Sorry for not proofreading carefully.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.