Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/360.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 通过列表理解将列表展平_Python_List_Python 2.7_List Comprehension - Fatal编程技术网

Python 通过列表理解将列表展平

Python 通过列表理解将列表展平,python,list,python-2.7,list-comprehension,Python,List,Python 2.7,List Comprehension,我正在尝试使用python中的列表理解功能将列表展平。我的清单有点像 [[1, 2, 3], [4, 5, 6], 7, 8] 只是为了打印这个列表中的单个项目,我写了这个代码 def flat(listoflist): for item in listoflist: if type(item) != list: print item else:

我正在尝试使用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
list2=[item if type(item)!=list else num for num for num in item for num in item for list1]
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
TypeError:“int”对象不可编辑

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

您正在尝试遍历一个数字,但您不能这样做(因此出现错误)

如果您使用的是python 2.7:

>>> from compiler.ast import flatten
>>> flatten(l)
[1, 2, 3, 4, 5, 6, 7, 8]
但请注意,该模块现在已被弃用,并且不再存在于Python3中

>>> 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
相比,速度会慢一些):


使用生成器的替代解决方案:

import collections

def flatten(iterable):
    for item in iterable:
        if isinstance(item, collections.Iterable) and not isinstance(item, str):  # `basestring` < 3.x
            yield from item  # `for subitem in item: yield item` < 3.3
        else:
            yield item

>>> list(flatten([[1, 2, 3], [4, 5, 6], 7, 8]))
[1, 2, 3, 4, 5, 6, 7, 8]
导入集合
def展平(可调):
对于iterable中的项目:
如果isinstance(item,collections.Iterable)而不是isinstance(item,str):#`basestring`<3.x
项目#`的收益率对于项目中的子项目:收益率项目`<3.3
其他:
收益项目
>>>列表(展平([[1,2,3],[4,5,6],7,8]))
[1, 2, 3, 4, 5, 6, 7, 8]

没有人给出通常的答案:

def flat(l):
  return [y for x in l for y in x]

在StackOverflow中有很多重复的问题。

这对于使用2.x的询问者来说是非常好的,但值得注意的是,3.x用户应该使用
str
而不是
basestring
@Ashwini如果我的元素是dict而不是integer类型,该怎么办?@AnuragSharma小示例?@AshwiniChaudhary例如-->[{'ascdd':'skj},{'fd':'srsrsr}],{'dsf':'ds','ds':'dsffd}]@AnuragSharma本例的预期输出是什么?类型检查列表是个坏主意。如果
l
[[1,2,3],[4,5,6],7,888]
,则第一个解决方案产生
[1,2,3,4,5,6,7,8,8,8]
。删除第一位,但遗憾的是,我的另一个解决方案在python 3中不起作用。您的代码不适用于OP提供的列表,因为他的列表包含不可编辑的对象,即整数。但是,如果列表中的每一项都是iterable对象,那么代码就可以工作。请参阅下面我的评论。感谢您指出这一点-我实际上需要找一点时间来处理这一点,并抓住要点…可能一个解释也会有所帮助。此解决方案使用递归。对于嵌套列表中的每个元素,检查该元素是整数还是列表。如果是整数,则将该整数追加到列表nn中。如果嵌套列表中的元素是列表,则调用递归函数,对子列表的处理方式与对初始嵌套列表的处理方式相同。然后在nn中再次附加不是列表的元素。nn的输出将是一个非嵌套列表。大家好!伟大的现在请添加此信息。完成-Namasté。
def nnl(nl):    # non nested list

    nn = []

    for x in nl:
        if type(x) == type(5):
            nn.append(x)

    if type(x) == type([]):
        n = nnl(x)

        for y in n:
            nn.append(y)
    return nn

print (nnl([[9, 4, 5], [3, 8,[5]], 6]))  # output: [9, 4, 5, 3, 8, 5, 6]
def nnl(nl):    # non nested list

    nn = []

    for x in nl:
        if type(x) == type(5):
            nn.append(x)

    if type(x) == type([]):
        n = nnl(x)

        for y in n:
            nn.append(y)
    return nn

print (nnl([[9, 4, 5], [3, 8,[5]], 6]))  # output: [9, 4, 5, 3, 8, 5, 6]