在嵌套列表中连接项目 Python
假设你有一个这样的列表:
['a', '1' ,['c', 'd',['e',['f', '123']]]]
我想把每个里面的小列表里的东西连接起来,最后得到:
['a1',['cd',['e',['f123']]]]
我可以把一个列表里的东西连接起来,但到现在为止还没成功做到这一点,任何帮助都非常感谢!
2 个回答
1
这里有一个非递归的解决方案:
步骤如下:
- 把字符串合并在一起
- 把列表反转
- 把字符串简化成嵌套列表。
虽然这个方法可能没有递归的版本那么优雅,但如果列表嵌套得很深,它就不会导致栈溢出。
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]])
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']]]]