0

Let's say I have a list of tuples currently sorted by the first element :

tuple_list = [(1, "hello", "apple"), (1, "no", "orange"),
    (2, "bye", "grape"), (3, "okay", "banana"),
    (4, "how are you?", "raisin"), (4, "I'm doing well", "watermelon")]

I want to turn this list of tuples into a list of list of tuples based on the first element of each tuple.

For example:

new_tuple_list = [[(1, "hello", "apple"), (1, "no", "orange")],
    [(2, "bye", "grape")], [(3, "okay", "banana")],
    [(4, "how are you?", "raisin"), (4, "I'm doing well", "watermelon")]]
poke
  • 369,085
  • 72
  • 557
  • 602
Ziv Lotzky
  • 45
  • 8

2 Answers2

2

Use itertools.groupby to group items based on the integers:

from itertools import groupby

lst = [list(g)for _, g in groupby(tuple_list, lambda x: x[0])]
print(lst)

[[(1, 'hello', 'apple'), (1, 'no', 'orange')], 
 [(2, 'bye', 'grape')], 
 [(3, 'okay', 'banana')], 
 [(4, 'how are you?raisin'), (4, "I'm doing well", 'watermelon')]]
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
2

You can use itertools.groupby for this:

[list(x) for k, x in itertools.groupby(tuple_list, operator.itemgetter(0))]
poke
  • 369,085
  • 72
  • 557
  • 602