【问题标题】:Remove and concat elements from a list while iterating迭代时从列表中删除和连接元素
【发布时间】: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


    【解决方案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)
    

    【讨论】:

      猜你喜欢
      • 2018-07-18
      • 2016-07-19
      • 2011-04-02
      • 2015-06-30
      • 2016-11-21
      • 2013-01-23
      • 2010-12-07
      • 1970-01-01
      相关资源
      最近更新 更多