Merge nested list items based on a repeating value

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

    marker_array = [
        ['hard','2','soft'],
        ['heavy','2','light'],
        ['rock','2','feather'],
        ['fast','3'], 
        ['turtle','4','wet'],
    ]
    
    data = {}
    
    for arr in marker_array:
        if len(arr) == 2:
            arr.append('')
    
        (first, index, last) = arr
        firsts, lasts = data.setdefault(index, [[],[]])
        firsts.append(first)
        lasts.append(last)
    
    
    results = []
    
    for key in sorted(data.keys()):
        current = [
            " ".join(data[key][0]),
            key,
            " ".join(data[key][1])
        ]
    
        if current[-1] == '':
            current = current[:-1]
    
        results.append(current)
    
    
    
    print results
    
    --output:--
    [['hard heavy rock', '2', 'soft light feather'], ['fast', '3'], ['turtle', '4', 'wet']]
    

提交回复
热议问题