使用理解来压平嵌套列表的最后一层



如何压平嵌套列表的最后一层?

lista = [['a'],['b']]
listb = [['c']]
nested = [lista, listb]
# [[['a'], ['b']], [['c']]]
# how to get [['a', 'b'], ['c']]?
[[x for x in y] for y in nested]
# gives [[['a'], ['b']], [['c']]]

我试过拆包,但在列表理解中被否决了。

对于更多的上下文,最后一个元素总是一个元素列表的原因是我通过使用得到这个结果

[myfunc(x) for x in y for y in other_nested_list]
lista = [['a'],['b']]
listb = [['c']]
nested = [lista, listb]
# [[['a'], ['b']], [['c']]]
# how to get [['a', 'b'], ['c']]?
print([[x for x in y] for y in nested])
# gives [[['a'], ['b']], [['c']]]

#simple solution:
print([[x[0] for x in y] for y in nested])
# gives [['a', 'b'], ['c']]

#solution with itertools (it will work to list with multiple items inside it too):
import itertools
print([list(itertools.chain.from_iterable([x for x in y])) for y in nested])
# gives [['a', 'b'], ['c']]

#solution with `unlist()` (== with itertools still):
def unlist(lst):
return list(itertools.chain.from_iterable(lst))
print([unlist([x for x in y]) for y in nested])
# gives [['a', 'b'], ['c']]

列表理解是不需要的,所以如果由于其他原因不是固定的要求,您可以将列表与+:一起添加

lista = ['a','b']
listb = ['c']
nested = [lista] + [listb]
print(nested)

输出:

[['a', 'b'], ['c']]

您可以使用列表理解:

lista = ['a','b']
listb = ['c']
nested = [[lista], [listb]]
listc = [j for i in nested for j in i]
print(listc)

或者你可以使用itertools

import itertools
lista = ['a','b']
listb = ['c']
nested = [[lista], [listb]]
listc = list(itertools.chain.from_iterable(nested))
print(listc)

输出:

[['a', 'b'], ['c']]
[['a', 'b'], ['c']]

更新

你可以使用上面的两个例子,然后使用

lista = [[['a'], ['b']], [['c']]]
listb = [j for i in lista for j in i]
listc = [listb[0] + listb[1], listb[2]]
print(listc)

输出

[['a', 'b'], ['c']]

您可以创建自己的函数,该函数将递归运行,您将告诉您希望在哪个级别解压缩您的列表

nested = [[['a'], ['b']], [['c']]]
def unstack(l, level):
if level == 1:
return l[0]
res = []
for i in l:
if isinstance(i, list):
res.append(unstack(i, level-1))
else:
res.append(i)
return res
unstack(nested, 3)  # [['a', 'b'], ['c']]

它将适用于每个嵌套层,您必须提供要取消堆叠此列表的级别。

最新更新