Merge nested list items based on a repeating value

前端 未结 5 1320
面向向阳花
面向向阳花 2021-01-25 15:32

Although poorly written, this code:

marker_array = [[\'hard\',\'2\',\'soft\'],[\'heavy\',\'2\',\'light\'],[\'rock\',\'2\',\'feather\'],[\'fast\',\'3\'], [\'turtl         


        
5条回答
  •  余生分开走
    2021-01-25 16:17

    from collections import defaultdict
    d1 = defaultdict(list)
    d2 = defaultdict(list)
    for pxa in marker_array:
        d1[pxa[1]].extend(pxa[:1])
        d2[pxa[1]].extend(pxa[2:])
    
    res = [[' '.join(d1[x]), x, ' '.join(d2[x])] for x in sorted(d1)]
    

    If you really need 2-tuples (which I think is unlikely):

    for p in res:
        if not p[-1]:
            p.pop()
    

提交回复
热议问题