通过列表理解来展平列表列表 [英] flatten list of list through list comprehension
本文介绍了通过列表理解来展平列表列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用 Python 中的列表理解来展平列表.我的清单有点像
[[1, 2, 3], [4, 5, 6], 7, 8]
只是为了打印这个列表中的单个项目,我写了这段代码
def flat(listoflist):对于 listoflist 中的项目:如果类型(项目)!= 列表:打印项目别的:对于项目中的数量:打印编号>>>平面(列表 1)12345678
然后我使用相同的逻辑通过列表理解来展平我的列表我收到以下错误
list2 = [item if type(item) != list else num for num in item for item in list1]回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中类型错误:int"对象不可迭代
如何使用列表理解来展平这种类型的列表?
解决方案
>>>从集合导入可迭代>>>从 itertools 导入链
单线:
<预><代码>>>>list(chain.from_iterable(item if isinstance(item,Iterable) 和不是 isinstance(item, basestring) else [item] for item in lis))[1, 2, 3, 4, 5, 6, 7, 8]可读版本:
<预><代码>>>>def func(x): #在py3.x中使用`str`...如果 isinstance(x, Iterable) 而不是 isinstance(x, basestring):...返回 x...返回 [x]...>>>list(chain.from_iterable(func(x) for x in lis))[1, 2, 3, 4, 5, 6, 7, 8]#也适用于字符串>>>lis = [[1, 2, 3], [4, 5, 6], 7, 8, "foobar"]>>>list(chain.from_iterable(func(x) for x in lis))[1, 2, 3, 4, 5, 6, 7, 8, 'foobar']使用嵌套列表理解:(与 itertools.chain
相比会变慢):
I am trying to flatten a list using list comprehension in python. My list is somewhat like
[[1, 2, 3], [4, 5, 6], 7, 8]
just for printing then individual item in this list of list I wrote this code
def flat(listoflist):
for item in listoflist:
if type(item) != list:
print item
else:
for num in item:
print num
>>> flat(list1)
1
2
3
4
5
6
7
8
Then I used the same logic to flatten my list through list comprehension I am getting the following error
list2 = [item if type(item) != list else num for num in item for item in list1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
How can I flatten this type of list-of-list using using list comprehension ?
解决方案
>>> from collections import Iterable
>>> from itertools import chain
One-liner:
>>> list(chain.from_iterable(item if isinstance(item,Iterable) and
not isinstance(item, basestring) else [item] for item in lis))
[1, 2, 3, 4, 5, 6, 7, 8]
A readable version:
>>> def func(x): #use `str` in py3.x
... if isinstance(x, Iterable) and not isinstance(x, basestring):
... return x
... return [x]
...
>>> list(chain.from_iterable(func(x) for x in lis))
[1, 2, 3, 4, 5, 6, 7, 8]
#works for strings as well
>>> lis = [[1, 2, 3], [4, 5, 6], 7, 8, "foobar"]
>>> list(chain.from_iterable(func(x) for x in lis))
[1, 2, 3, 4, 5, 6, 7, 8, 'foobar']
Using nested list comprehension:(Going to be slow compared to itertools.chain
):
>>> [ele for item in (func(x) for x in lis) for ele in item]
[1, 2, 3, 4, 5, 6, 7, 8, 'foobar']
这篇关于通过列表理解来展平列表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文