Convert Tuples list to nested list using Python

I want to convert a list of tuples to a nested list using Python. How to do it?

I have a sorted list of tuples (sorted by a second value):

[(1, 5),  (5, 4), (13, 3), (4, 3), (3, 2), (14, 1), (12, 1), 
 (10, 1), (9, 1), (8, 1),  (7, 1), (6, 1), (2, 1)]

Now I want it to be like this (the second value is ignored and nested in lists):

[ [1], [5], [13, 4], [3], [14, 12, 10, 9, 8, 7, 6, 2] ]

I saw other topics here with mapused for such things, but I do not quite understand this. Can someone give an idea of ​​the β€œcorrect” python way to do this?

+3
source share
5 answers
from operator import itemgetter
from itertools import groupby

lst = [(1, 5),  (5, 4), (13, 3), (4, 3), (3, 2), (14, 1),
       (12, 1), (10, 1), (9, 1), (8, 1),  (7, 1), (6, 1), (2, 1)]

result = [[x for x, y in group]
          for key, group in groupby(lst, key=itemgetter(1))]

groupby(lst, key=itemgetter(1)) lst, ( ) . [x for x, y in group] 0- .

+11

, itertools.groupby:

>>> lst = [(1, 5),  (5, 4), (13, 3), (4, 3), (3, 2), (14, 1), (12, 1), 
 (10, 1), (9, 1), (8, 1),  (7, 1), (6, 1), (2, 1)]
>>> from operator import itemgetter 
>>> import itertools
>>> [map(itemgetter(0), group) for (key,group) in itertools.groupby(lst, itemgetter(1))]
[[1], [5], [13, 4], [3], [14, 12, 10, 9, 8, 7, 6, 2]]
>>> 

: groupby , , , , . itemgetter (1) , x [1] x. groupby - , , , (itemgetter (0), group).

+2

, , :

d = {}

a = [(1,5), (5,4), (13,3), (4,3), (3,2), (14,1), (12,1)]

for value in a:
     if value[0] not in d:
         d[ value[0] ] = []
     d[ value[0] ].append( a[1] )

print d.values()
+1

:

n_list = []
c_snd = None
for (fst, snd) in o_list:
  if snd == c_snd: n_list[-1].append(fst)
  else:
    c_snd = snd
    n_list.append([fst])

: c_snd . , n_list , fst, fst n_list.

+1

I don't know how fast it will be for large sets, but you can do something like this:

input = [
    (1,  5), (5,  4), (13, 3), (4, 3), (3, 2), (14, 1),
    (12, 1), (10, 1), (9,  1), (8, 1), (7, 1), (6,  1),
    (2,  1)
]

output = [[] for _ in xrange(input[0][1])]
for value, key in input:
    output[-key].append(value)

print output # => [[1], [5], [13, 4], [3], [14, 12, 10, 9, 8, 7, 6, 2]]
0
source

Source: https://habr.com/ru/post/1724866/


All Articles