Merge nested list items based on a repeating value

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

    marker_array = [['hard','2','soft'],['heavy','2','light'],['rock','2','feather'],['fast','3'], ['turtle','4','wet']]
    marker_array_DS = []
    marker_array_hit = []
    
    for i in range(len(marker_array)):
        if marker_array[i][1] not in marker_array_hit:
            marker_array_hit.append(marker_array[i][1])
    
    for i in marker_array_hit:
        lists = [item for item in marker_array if item[1] == i]
        temp = []
        first_part = ' '.join([str(item[0]) for item in lists])
        temp.append(first_part)
        temp.append(i)
        second_part = ' '.join([str(item[2]) for item in lists if len(item) > 2])
        if second_part != '':
            temp.append(second_part);
        marker_array_DS.append(temp)
    
    print marker_array_DS
    

    I learned python for this because I'm a shameless rep whore

提交回复
热议问题