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

前端 未结 3 587
星月不相逢
星月不相逢 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:41

    Try this,

    Section = [('1', '1.1', '1.2'), ('1', '2', '2.2', '3'), ('1', '1.2', '3.2', '3.5')] 
    Page = [('1', '1', '3'), ('1', '2', '2', '2'), ('1', '2', '3', '5')]
    Titles = [('General', 'Info', 'Titles'), ('More', 'Info', 'Section', 'Here'), ('Another', 'List', 'Of', 'Strings')]
    
    # Flat a list of tuples into a list
    l1 = [item for sublist in Section for item in sublist]
    l2 = [item for sublist in Page for item in sublist]
    l3 = [item for sublist in Titles for item in sublist]
    
    # Python2, `zip` returns a list of tuples
    #result = zip(*sorted(zip(l1, l2, l3), key=lambda x:float(x[0])))
    
    # Python3, `zip` returns an iterator of tuples
    result = list(zip(*sorted(zip(l1, l2, l3), key=lambda x:float(x[0]))))
    
    print(result)
    # Output
    [   ('1', '1', '1', '1.1', '1.2', '1.2', '2', '2.2', '3', '3.2', '3.5'), 
        ('1', '1', '1', '1', '3', '2', '2', '2', '2', '3', '5'), 
        ('General', 'More', 'Another', 'Info', 'Titles', 'List', 'Info', 'Section', 'Here', 'Of', 'Strings')]
    

提交回复
热议问题