【发布时间】:2020-11-25 07:53:31
【问题描述】:
我正在使用 python,我有以下列表:
mylist = ['Module(stmt* body, type_ignore *type_ignores)', '| Interactive(stmt* body)', 'FunctionDef(identifier name, arguments args,','stmt* body, expr* decorator_list, expr? returns,','string? type_comment)']
如果第二个元素不是以) 结尾并且前一个元素不是以| 开头,我想将列表的一个元素与前一个元素连接,然后删除第二个元素。例如,mylist 应转换为:
mylist = ['Module(stmt* body, type_ignore *type_ignores)', '| Interactive(stmt* body)', 'FunctionDef(identifier name, arguments args, stmt* body, expr* decorator_list, expr? returns, string? type_comment)']
我写了以下递归代码:
def test(line1, line2):
if line1[-1] != ')' and line2[0] != '|':
return True, line1 + line2
else:
return False, line1
def concat_rule(lines):
for index in range(len(lines)):
if index + 1 >= len(lines):
return lines
value = test(lines[index], lines[index + 1])
if value[0]:
lines[index] = value[1]
del lines[index + 1]
break
if value[0]:
return concat_rule(lines)
它有效,但我想知道它是否存在一个包含完整列表的最简单的解决方案。
【问题讨论】:
标签: python-3.x list concatenation