0

How could I join the sublist inside a list? I had done this,

from collections import deque
new_list = []

def sort_sequence(lst):
    lst = "".join([str(i) for i in lst])
    lst = [list(i + "0") for i in lst.split("0") if i]
    lst = [[int(j) for j in i] for i in lst] 
    lst = [sorted(k) for k in lst]

    for i  in range(len(lst)):
        item = deque(lst[i])
        item.rotate(-1)
        new_list.append(list(item))
    print(new_list)
        
    
sort_sequence([1,3,2,0,5,4,6,0,2,3,4,0])

For example:

I want this list [[1, 2, 3, 0], [4, 5, 6, 0], [2, 3, 4, 0]] as [1, 2, 3, 0, 4, 5, 6, 0, 2, 3, 4, 0]

Please help me with this.

3 Answers3

0

No need to import any module. Recursion will do it.

new_list = []

def sort_sequence(lst):
    for i in lst:
        if isinstance(i,list):
            sort_sequence(i) 
        else:
            new_list.append(i)
    print(new_list)   
    
sort_sequence([1,3,2,0,5,4,6,0,2,3,4,0])
0

You can use itertools.chain.from_iterable() https://docs.python.org/3/library/itertools.html#itertools.chain.from_iterable

In [1]: from itertools import chain

In [2]: a = [[1, 2, 3, 0], [4, 5, 6, 0], [2, 3, 4, 0]]

In [3]: b = list(chain.from_iterable(a))

In [4]: b
Out[4]: [1, 2, 3, 0, 4, 5, 6, 0, 2, 3, 4, 0]
Ron Serruya
  • 3,988
  • 1
  • 16
  • 26
0

Instead of appending to the list, you can add to it and get your desired result. Use this code:

from collections import deque


def sort_sequence(lst):
    lst = "".join([str(i) for i in lst])
    lst = [list(i + "0") for i in lst.split("0") if i]
    lst = [[int(j) for j in i] for i in lst] 
    lst = [sorted(k) for k in lst]
    new_list = []
    for i  in range(len(lst)):
        item = deque(lst[i])
        item.rotate(-1)
        new_list = new_list + list(item)
    print(new_list)
        
    
sort_sequence([1,3,2,0,5,4,6,0,2,3,4,0])
Mohsin Ali
  • 11
  • 1