Python,根据索引将嵌套列表中的字符串连接起来

问题描述 投票:2回答:1

我正在尝试基于字符串中的相似值(基于不同的索引)来连接字符串。目前,该代码段最多可以连续三个单词正常工作,但可以中断四个单词。

例如:

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']

非常感谢您的帮助!

python nested-lists
1个回答
0
投票

这将完成:

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']
© www.soinside.com 2019 - 2024. All rights reserved.