Combing 2D list of tuples and then sorting them in Python

前端 未结 3 588
星月不相逢
星月不相逢 2021-01-18 04:56

Update: The list are filled with strings I edited the list to show this

I have 3 different list such as

Section = [(\'1\', \'1.1\', \'1.2\'), (\'1\',         


        
3条回答
  •  甜味超标
    2021-01-18 05:34

    My approach. List comprehension and no need to import modules. I think its fast, and its very simple.

    EDIT: I've added an unsorted approach and a sorted approach.

    #Unsorted
    newList =[
        [item for sublist in Section for item in sublist],
        [item for sublist in Page for item in sublist],
        [item for sublist in Titles for item in sublist]
        ]
    
    print newList
    #Output
    #[[1, 1.1, 1.2, 1, 2, 2.2, 3, 1, 1.2, 3.2, 3.5], 
    # [1, 1, 3, 1, 2, 2, 2, 1, 2, 3, 5], 
    # ['General', 'Info', 'Titles', 'More', 'Info', 'Section', 'Here', 'Another', 'List', 'Of', 'Strings']]
    
    #Sort first two lists afterwards, if desired
    for i in range(2):
        newList[i].sort()
    
    print newList
    #Output
    #[[1, 1, 1, 1.1, 1.2, 1.2, 2, 2.2, 3, 3.2, 3.5], 
    # [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 5], 
    # ['General', 'Info', 'Titles', 'More', 'Info', 'Section', 'Here', 'Another', 'List', 'Of', 'Strings']]
    

提交回复
热议问题