我正在使用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)
它可以工作,但我想知道它是否存在包含最简单清单的最简单解决方案。
答案 0 :(得分:1)
无需递归-您可以使用简单的循环。 (我不确定列表理解是否可以帮助您。)
这里是可以进行就地修改的版本:
index = 1
while index < len(mylist):
if mylist[index - 1][-1] != ')' and mylist[index][0] != '|':
mylist[index - 1] += mylist.pop(index)
else:
index += 1
这是制作新列表的版本:
output = [mylist[0]]
for item in mylist[1:]:
if output[-1][-1] != ')' and item[0] != '|':
output[-1] += item
else:
output.append(item)