编写列表理解以拼合嵌套列表 [英] Writing a list comprehension to flatten a nested list
问题描述
我有一个包含列表和数字的嵌套列表.
I have a nested list mixed with list and numbers.
nested = [[1, 2, 3], [4, 5, 6], [7, 8], [9], 10, 11]
嵌套列表仅包含数字,而永远不会包含更多列表.
The nested lists only contain numbers, they'll never contain more lists.
是否可以编写列表理解以从嵌套"列表中创建新列表,并产生以下输出?
Is it possible to write a list comprehension to make new list from the 'nested' list, producing the following output?
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
这是我的尝试(代码不起作用)
This was my attempt( code is not working)
[num if isinstance(item, list) for num in item else item for item in nested]
推荐答案
您需要将实例测试放入循环中,以便可以从嵌套列表中提取元素:
You need to put your instance test in a loop, so you can extract the elements from a nested list:
[num for item in nested for num in (item if isinstance(item, list) else (item,))]
演示:
>>> nested = nested = [[1, 2, 3], [4, 5, 6], [7, 8], [9], 10, 11]
>>> [num for item in nested for num in (item if isinstance(item, list) else (item,))]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
如果您首先将其表示为一组for
循环,则将有所帮助;您的尝试基本上是这样做的:
It helps if you first express this as a set of for
loops; your attempt essentially did this:
for item in nested:
_element = num if isinstance(item, list) for num in item else item
result.append(_element)
这不是真正有效的Python.
which is not really valid Python.
我上面的列表理解是这样做的:
My list comprehension above instead does this:
for item in nested:
_iterable = item if isinstance(item, list) else (item,)
for num in _iterable:
_element = num
result.append(_element)
这篇关于编写列表理解以拼合嵌套列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!