Merge nested list items based on a repeating value

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

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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))
    
    0 讨论(0)
  • 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()
    
    0 讨论(0)
  • 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']]
    
    0 讨论(0)
提交回复
热议问题