是一个简短的语法连接列表列表到一个单一的列表(或迭代器)在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
当前回答
对于无限嵌套的元素,这是递归工作的:
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)
来晚了,但是…
我是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]
I had a similar problem when I had to create a dictionary that contained the elements of an array and their count. The answer is relevant because, I flatten a list of lists, get the elements I need and then do a group and count. I used Python's map function to produce a tuple of element and it's count and groupby over the array. Note that the groupby takes the array element itself as the keyfunc. As a relatively new Python coder, I find it to me more easier to comprehend, while being Pythonic as well.
在我讨论代码之前,这里有一个我必须首先平化的数据示例:
{ "_id" : ObjectId("4fe3a90783157d765d000011"), "status" : [ "opencalais" ],
"content_length" : 688, "open_calais_extract" : { "entities" : [
{"type" :"Person","name" : "Iman Samdura","rel_score" : 0.223 },
{"type" : "Company", "name" : "Associated Press", "rel_score" : 0.321 },
{"type" : "Country", "name" : "Indonesia", "rel_score" : 0.321 }, ... ]},
"title" : "Indonesia Police Arrest Bali Bomb Planner", "time" : "06:42 ET",
"filename" : "021121bn.01", "month" : "November", "utctime" : 1037836800,
"date" : "November 21, 2002", "news_type" : "bn", "day" : "21" }
是来自Mongo的查询结果。下面的代码将这样的列表集合平铺开来。
def flatten_list(items):
return sorted([entity['name'] for entity in [entities for sublist in
[item['open_calais_extract']['entities'] for item in items]
for entities in sublist])
首先,我将提取所有的“实体”集合,然后对于每个实体集合,遍历字典并提取name属性。
对于无限嵌套的元素,这是递归工作的:
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']
总是有reduce(不推荐使用functools):
>>> x = [ [ 'a', 'b'], ['c'] ]
>>> for el in reduce(lambda a,b: a+b, x, []):
... print el
...
__main__:1: DeprecationWarning: reduce() not supported in 3.x; use functools.reduce()
a
b
c
>>> import functools
>>> for el in functools.reduce(lambda a,b: a+b, x, []):
... print el
...
a
b
c
>>>
不幸的是,用于列表连接的加号操作符不能用作函数——或者幸运的是,如果为了提高可见性,您希望lambdas变得更丑一些。