通过列表理解拼合列表 [英] flatten list of list through list comprehension

查看:61
本文介绍了通过列表理解拼合列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用python中的列表理解来扁平化列表.我的清单有点像

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

单线:

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

可读版本:

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

使用嵌套列表理解:(与itertools.chain相比要慢一些):

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆