我试图在python中使用list comprehension来压缩列表。我的清单有点像
[[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
如何使用列表推导来展平这种类型的列表?
答案 0 :(得分:9)
>>> 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
相比会变慢):
>>> [ele for item in (func(x) for x in lis) for ele in item]
[1, 2, 3, 4, 5, 6, 7, 8, 'foobar']
答案 1 :(得分:9)
没有人给出通常的答案:
def flat(l):
return [y for x in l for y in x]
StackOverflow周围有这个问题的愚蠢。
答案 2 :(得分:3)
你试图遍历一个你不能做的数字(因此错误)。
如果您使用的是python 2.7:
>>> from compiler.ast import flatten
>>> flatten(l)
[1, 2, 3, 4, 5, 6, 7, 8]
但请注意,该模块现已弃用,并且在Python 3中不再存在
答案 3 :(得分:3)
使用发电机的替代解决方案:
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]
答案 4 :(得分:1)
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]