通过列表理解拼合列表

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


[[1, 2, 3], [4, 5, 6], 7, 8]

只是为了打印,然后在此列表中的单个项目,我编写了此代码


   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

然后我使用相同的逻辑通过列表理解来整理列表,但出现以下错误


    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

如何使用列表理解来展平这种类型的列表?


守着星空守着你
浏览 195回答 3
3回答

繁星coding

>>> from collections import Iterable>>> from itertools import chain单线:>>> list(chain.from_iterable(item if isinstance(item,Iterable) and&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; not isinstance(item, basestring) else [item] for item in lis))[1, 2, 3, 4, 5, 6, 7, 8]可读版本:>>> def func(x):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;#use `str` in py3.x&nbsp;...&nbsp; &nbsp; &nbsp;if isinstance(x, Iterable) and not isinstance(x, basestring):&nbsp;...&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return x...&nbsp; &nbsp; &nbsp;return [x]...&nbsp;>>> 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))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;[1, 2, 3, 4, 5, 6, 7, 8, 'foobar']使用嵌套列表理解:(与相比,速度会很慢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']

ITMISS

没有人给出通常的答案:def&nbsp;flat(l): &nbsp;&nbsp;return&nbsp;[y&nbsp;for&nbsp;x&nbsp;in&nbsp;l&nbsp;for&nbsp;y&nbsp;in&nbsp;x]在StackOverflow周围有这个问题的虚假信息。

潇潇雨雨

您正在尝试遍历一个数字,而这个数字是您无法做到的(因此会出现错误)。如果您使用的是python 2.7:>>> from compiler.ast import flatten>>> flatten(l)[1, 2, 3, 4, 5, 6, 7, 8]但请注意,该模块现已弃用,并且在Python 3中不再存在
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python