-3

I have list of 2-elements tuples:

[(7, 3), (4, 3), (5, 3), (6, 3), (0, 1), (1, 1), (2, 1), (3, 1)]

And I want to convert it to another list of tuples. Each list contains elements with the same second index from first list.

So in this case result should look:

[(7, 4, 5, 6), (0, 1, 2, 3)]

because 7, 4, 5, and 6 are paired with 3 while 0, 1, 2, 3 are paired with 1.

My attempt is to do it this way:

x = list(map(operator.itemgetter(0), sorted_countries))

but I still don't know how to group it, because my result is:

[7, 4, 5, 6, 0, 1, 2, 3]
  • 1
    What is the exact logic you are trying to implement? Taking the 1st element from each pair and then splitting the final list in half? How did you try and code this? Where did you go wrong? – Chris_Rands May 02 '17 at 13:11
  • 1
    this is way underspecified. what is the order? what if elements are mixed? – Karoly Horvath May 02 '17 at 13:12
  • Okay, at least it makes sense now. But you need to make an attempt at doing it first. If you get stuck, post the code and we can help with a specific problem. I'd probably start with a naive implementation with an intermediary dict, maybe storing them in sublists which you can later use to generate the final tuples. – Kenny Ostrom May 02 '17 at 13:24
  • In each tuple order is not important. I want to group in only by second index in tuples of input list – Mikołaj Henklewski May 02 '17 at 13:25
  • @MikołajHenklewski so if the second element was `(4, 1)` - what would the output be? (eg: are you looking for consecutive keys or it doesn't matter...) – Jon Clements May 02 '17 at 13:27
  • 1
    If my input would look: `[(7, 3), (4, 1), (5, 3), (6, 3), (0, 1), (1, 1), (2, 1), (3, 1)]` My output would look: `[(7, 5, 6), (4, 0, 1, 2, 3)]` Again. Order inside of tuples is not important. Main goal is to group it. – Mikołaj Henklewski May 02 '17 at 13:35

4 Answers4

1

Depending on your use case this solution might be overgeneralized, but should work for all cases (i.e. initial tuples are not grouped by their second element). You need an OrderedDict here. If you want to avoid setdefault, you need an ordered defaultdict.

>>> from collections import OrderedDict
>>> l = [(7, 3), (4, 3), (5, 3), (6, 3), (0, 1), (1, 1), (2, 1), (3, 1)]
>>> 
>>> second2first = OrderedDict()
>>> for first, second in l:
...     second2first.setdefault(second, []).append(first)
... 
>>> result = [tuple(v) for v in second2first.values()]
>>> result
[(7, 4, 5, 6), (0, 1, 2, 3)]

The idea is to grab all the first values of your original tuples and append them to different lists based on the second element the first value is paired with. The OrderedDict is indexed by the first element of your tuples and is used to keep track of the creation order of the lists.

Afterwards, we just extract the values (lists) and convert them to tuples.

Community
  • 1
  • 1
timgeb
  • 76,762
  • 20
  • 123
  • 145
1

Have a look at itertools.groupby(). This can do the grouping for you.

Notice: the input has to be sorted by group key.

Example, to get your desired output:

import itertools
test=[(7, 3), (4, 3), (5, 3), (6, 3), (0, 1), (1, 1), (2, 1), (3, 1), (7, 3), (4, 3)]
groups = []
test.sort(key=lambda x:x[1])
for _, group in itertools.groupby(test, key=lambda x:x[1]):
    groups.append(tuple(elem for elem, _ in group))
print(groups)

As Jon Clements suggests, all of this can be done in a single line with nested list comprehensions:

groups = [tuple(el[0] for el in g) for k, g in itertools.groupby(sorted(test, key=lambda L: L[1]), key=lambda L: L[1])]
Christian König
  • 3,437
  • 16
  • 28
0
lt = [(7, 3), (4, 3), (5, 3), (6, 3), (0, 1), (1, 1), (2, 1), (3, 1)]

lt_part1 = lt[0:len(lt)//2] #[(7, 3), (4, 3), (5, 3), (6, 3)] 


list1 = []
list2 = [] 

list1.append( tuple([t[0]for t in lt_part1]) )
list2.append( tuple([t[1]for t in lt_part1]) )

print(list1)
print(list2)

RESULT:

[(7, 4, 5, 6)]
[(3, 3, 3, 3)]
Fuji Komalan
  • 1,979
  • 16
  • 25
0

At this time I am not able to get an inline solution... Hope the code snippet is useful if you need solution rather than clear one liner answer..

tupleList = [(7, 3), (4, 3), (5, 3), (6, 3), (0, 1), (1, 1), (2, 1), (3, 1)]
ex_dict = {}
for (x,y) in tupleList:
   try:
     if(ex_dict[y]):
        ex_dict[y] = ex_dict[y]+(x,)
   except:
     ex_dict[y]= (x,)

ex_list = list(ex_dict[x] for x in ex_dict)
print(ex_list)
Rajani B
  • 193
  • 5