如果上一個專案末尾有“\”,我需要與串列中的下一個專案合并。例子:
original_list = ['first.key=First value', 'second.key=Second value, first line\\',
'Second value, second line\\', 'Second value, third line\\', 'Second value, fourth
line', 'third.key=Third value']
預期結果是:
desired_list = ['first.key=First value', 'second.key=Second value,first line\\ Second
value, second line\\ Second value, third line\\ Second value, fourth line',
'third.key=Third value']
不要假設以 '\' 結尾的第一項是串列中的第二項。我不知道會是哪個。
uj5u.com熱心網友回復:
這是一個粗略的解決方案,但應該可以作業:
desired_list = original_list[:1]
for x in original_list[1:]:
if desired_list[-1].endswith('\\'):
desired_list[-1] = x
else:
desired_list.append(x)
print(desired_list)
如果您使用龐大的串列,可能值得考慮一些優化。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/420233.html
標籤:
上一篇:替換串列中的所有其他位置
