Concatenate strings in nested list based on index

Jon snow :

I am trying to concatenate strings based on the similar values in them (on different indices). At the moment, the snippet works fine for a maximum of three words in consecutive order, but breaks for four.

For example:

reg = [
        ['Abraham', 0.9, 1.6],
        ['King', 1.6, 2.4],
        ['Late', 2.4, 3.2],
        ['Moto', 11.3, 11.9],
        ['GP', 11.9, 12.7],
        ['Ferrari', 14.7, 15.1],
        ['GT-86', 15.1, 15.8],
        ['HP', 16.1, 16.6],
        ['Envy', 16.6, 17.0],
        ['16', 17.0, 17.4],
        ['DV', 17.4, 18.0]
    ]


temp_word = ''
result_lst = []
isBool = False

for indx, elem in enumerate(reg):
    try:
        if elem[2] == reg[indx+1][1]:
            if isBool:
                temp_word += elem[0] + reg[indx+1][0]
                result_lst.append(temp_word)
            else:
                temp_word = elem[0]
                isBool = not isBool
        else:
            temp_word = ''
    except IndexError:
        pass

print(result_lst)
#Output:

#['AbrahamKingLate', 'MotoGP', 'FerrariGT-86', 'HPEnvy', 'HPEnvyEnvy16', 'HPEnvyEnvy1616DV']   


# Desired: 
# ['AbrahamKingLate', 'MotoGP', 'FerrariGT-86', 'HPEnvy16DV']

Any help would be very much appreciated!

ekhumoro :

This can be done quite simply by saving the previous item and then comparing it to the current item, like this:

result = []
previous = None
for current in reg:
    if previous and current[1] == previous[2]:
        result[-1] += current[0]
    else:
        result.append(current[0])
    previous = current

print(result)

Output:

['AbrahamKingLate', 'MotoGP', 'FerrariGT-86', 'HPEnvy16DV']

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=3841&siteId=1