Merge nested list items based on a repeating value

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

    A different solution based on itertools.groupby:

    from itertools import groupby
    
    # normalizes the list of markers so all markers have 3 elements
    def normalized(markers):
        for marker in markers:
            yield marker + [""] * (3 - len(marker))
    
    def concatenated(markers):
      # use groupby to iterator over lists of markers sharing the same key
      for key, markers_in_category in groupby(normalized(markers), lambda m: m[1]):
        # get separate lists of left and right words
        lefts, rights = zip(*[(m[0],m[2]) for m in markers_in_category])
        # remove empty strings from both lists
        lefts, rights = filter(bool, lefts), filter(bool, rights)
        # yield the concatenated entry for this key (also removing the empty string at the end, if necessary)
        yield filter(bool, [" ".join(lefts), key, " ".join(rights)])
    

    The generator concatenated(markers) will yield the results. This code correctly handles the ['fast', '3'] case and doesn't return an additional third element in such cases.

提交回复
热议问题