4

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!

3 Answers 3

1

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']
Sign up to request clarification or add additional context in comments.

Comments

0

This will do it:

result = [reg[0]]

for item in reg[1:]:
    r_num = result[-1][2]
    r_name = result[-1][0]
    i_num = item[1]
    i_name = item[0]
    if i_num == r_num:
        result[-1] = [r_name+i_name] + item[1:]
    else:
        result.append(item)

result = [r[0] for r in result]

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

Comments

0

Try this:

names = []
first_elem = reg[0][0]

for ix, l in enumerate(reg[1:]):
    if l[1] == reg[ix][-1]:
        first_elem = first_elem + l[0]
    else:
        names.append(first_elem)
        first_elem = l[0]
names.append(first_elem)
print(names)

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.