Python 基于索引连接嵌套列表中的字符串
我试图根据字符串中的相似值(在不同的索引上)连接字符串。 目前,该代码段最多可以连续使用三个单词,但会中断四个单词 例如:Python 基于索引连接嵌套列表中的字符串,python,nested-lists,Python,Nested Lists,我试图根据字符串中的相似值(在不同的索引上)连接字符串。 目前,该代码段最多可以连续使用三个单词,但会中断四个单词 例如: 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],
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']
任何帮助都将不胜感激 这样就可以了:
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']
试试这个:
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']
只需保存上一项,然后将其与当前项进行比较,即可完成此操作,如下所示:
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)
输出:
['AbrahamKingLate', 'MotoGP', 'FerrariGT-86', 'HPEnvy16DV']