连接嵌套列表中的项目python

2024-05-02 11:49:00 发布

您现在位置:Python中文网/ 问答频道 /正文

给出如下清单:

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

如何将每个嵌套列表中的项串联起来,从而导致:

^{pr2}$

我可以在一个列表中连接项目,但迄今为止没有成功,任何帮助将不胜感激!在


Tags: 项目列表pr2
2条回答

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

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)

结果是:

^{pr2}$

下面是一个非递归解决方案:

步骤如下:

  1. 合并字符串
  2. 把名单倒过来
  3. 将字符串缩减为嵌套列表。在

它可能不比递归版本优雅,但是如果列表是深嵌套的,它不会炸毁堆栈。在

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]])

相关问题 更多 >