连接嵌套列表python中的项目

时间:2014-04-20 12:11:42

标签: python list nested concatenation

给出如下列表:

['a', '1' ,['c', 'd',['e',['f', '123']]]]

如何连接每个嵌套列表中的项目,结果如下:

['a1',['cd',['e',['f123']]]]

我可以在一个列表中连接项目,但到目前为止一直没有成功,任何帮助都将非常感谢!

2 个答案:

答案 0 :(得分:3)

这里的嵌套结构适合被递归算法遍历:

x = ['a', '1', ['c', 'd', ['e', ['f', '123']]]]

def recurse(y):
    left,right = [],None

    # Here we loop over the elements and whenever we encounter
    # another list, we recurse.  
    for elem in y:
        if isinstance(elem,list):
            right = recurse(elem)
        else:
            left.append(elem)

    # If there is no further nested list, return only the 
    # concatenated values, else return the concatenated values 
    # and the next list in the nest.
    if right is None:
        return ["".join(left)]
    else:
        return ["".join(left),right]

print recurse(x)

这个输出是:

['a1', ['cd', ['e', ['f123']]]]

答案 1 :(得分:1)

这是一个非递归解决方案:

以下是步骤:

  1. 合并字符串
  2. 反向列表
  3. 将字符串缩减为嵌套列表。
  4. 它可能不比递归版本优雅,但如果列表深度嵌套,它不会炸毁堆栈。

    def collapse(x):
        l = deque([x])
        result = []
        y = ""
    
        while l:
            p = l.popleft()
            for i in p:
                if isinstance(i, list):
                    result.append(y)
                    y = ""
                    l.append(i)
                    break
                else:
                    y = y + i
        result.append(y)
        return result
    
    
    x = ['a', '1', ['c', 'd', ['e', ['f', '123']]]]
    j = [ i for i in collapse(x)]
    j.reverse()
    print reduce(lambda x, y: [y, x], j[1:], [j[0]])