Merge nested list items based on a repeating value

前端 未结 5 1394
面向向阳花
面向向阳花 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:13

    Quick stab at it... use itertools.groupby to do the grouping for you, but do it over a generator that converts the 2 element list into a 3 element.

    from itertools import groupby
    from operator import itemgetter
    
    marker_array = [['hard','2','soft'],['heavy','2','light'],['rock','2','feather'],['fast','3'], ['turtle','4','wet']]  
    
    def my_group(iterable):
        temp = ((el + [''])[:3] for el in marker_array)
        for k, g in groupby(temp, key=itemgetter(1)):
            fst, snd = map(' '.join, zip(*map(itemgetter(0, 2), g)))
            yield filter(None, [fst, k, snd])
    
    print list(my_group(marker_array))
    

提交回复
热议问题