是一个简短的语法连接列表列表到一个单一的列表(或迭代器)在python?
例如,我有一个列表,如下所示,我想迭代a,b和c。
x = [["a","b"], ["c"]]
我能想到的最好的是如下。
result = []
[ result.extend(el) for el in x]
for el in result:
print el
是一个简短的语法连接列表列表到一个单一的列表(或迭代器)在python?
例如,我有一个列表,如下所示,我想迭代a,b和c。
x = [["a","b"], ["c"]]
我能想到的最好的是如下。
result = []
[ result.extend(el) for el in x]
for el in result:
print el
当前回答
这就是所谓的扁平化,有很多实现。
这个怎么样,尽管它只适用于1级深嵌套:
>>> x = [["a","b"], ["c"]]
>>> for el in sum(x, []):
... print el
...
a
b
c
从这些链接中,显然最完整的-fast-elegant-etc实现如下:
def flatten(l, ltypes=(list, tuple)):
ltype = type(l)
l = list(l)
i = 0
while i < len(l):
while isinstance(l[i], ltypes):
if not l[i]:
l.pop(i)
i -= 1
break
else:
l[i:i + 1] = l[i]
i += 1
return ltype(l)
其他回答
来晚了,但是…
我是python的新手,有lisp的背景。这是我想出的(检查lulz的var名称):
def flatten(lst):
if lst:
car,*cdr=lst
if isinstance(car,(list,tuple)):
if cdr: return flatten(car) + flatten(cdr)
return flatten(car)
if cdr: return [car] + flatten(cdr)
return [car]
似乎有用。测试:
flatten((1,2,3,(4,5,6,(7,8,(((1,2)))))))
返回:
[1, 2, 3, 4, 5, 6, 7, 8, 1, 2]
对于无限嵌套的元素,这是递归工作的:
def iterFlatten(root):
if isinstance(root, (list, tuple)):
for element in root:
for e in iterFlatten(element):
yield e
else:
yield root
结果:
>>> b = [["a", ("b", "c")], "d"] >>> list(iterFlatten(b)) ['a', 'b', 'c', 'd']
这就是所谓的扁平化,有很多实现。
这个怎么样,尽管它只适用于1级深嵌套:
>>> x = [["a","b"], ["c"]]
>>> for el in sum(x, []):
... print el
...
a
b
c
从这些链接中,显然最完整的-fast-elegant-etc实现如下:
def flatten(l, ltypes=(list, tuple)):
ltype = type(l)
l = list(l)
i = 0
while i < len(l):
while isinstance(l[i], ltypes):
if not l[i]:
l.pop(i)
i -= 1
break
else:
l[i:i + 1] = l[i]
i += 1
return ltype(l)
您所描述的就是所谓的将列表扁平化,有了这些新知识,您将能够在谷歌上找到许多解决方案(没有内置的扁平化方法)。以下是其中一个,来自http://www.daniel-lemire.com/blog/archives/2006/05/10/flattening-lists-in-python/:
def flatten(x):
flat = True
ans = []
for i in x:
if ( i.__class__ is list):
ans = flatten(i)
else:
ans.append(i)
return ans
import itertools
a = [['a','b'], ['c']]
print(list(itertools.chain.from_iterable(a)))
这给了
['a', 'b', 'c']