如果“\\”位于项目末尾,则连接 python 列表中的项目
Concatenate items in a python list if '\\' is at the end of item
如果上一项末尾有“\”,我需要与列表中的下一项合并。示例:
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']
不要假定以“\”结尾的第一项是列表中的第二项。不知道会是哪个
这是一个粗略的解决方案,但应该有效:
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)
如果您使用庞大的列表,可能值得考虑一些优化。
如果上一项末尾有“\”,我需要与列表中的下一项合并。示例:
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']
不要假定以“\”结尾的第一项是列表中的第二项。不知道会是哪个
这是一个粗略的解决方案,但应该有效:
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)
如果您使用庞大的列表,可能值得考虑一些优化。