2013-10-11 44 views

回答

1

“最Python的” 可争论不休。我更喜欢嵌套的列表理解来拼合嵌套列表。

B = [element for sublist in A for element in sublist] 

当它归结到它,使用,因为你可能谁最经常与你的代码交互的人什么是最可读性

2
import operator 
reduce(operator.add, A) 

reduce(lambda x,y:x+y, A) 
+0

太棒了,它的工作原理!但你介意解释一下吗?这个 –

+0

背后的基本原理是什么?你可以看看[reduce](http://docs.python.org/2/library/functions.html#reduce)。在这种情况下,'operator.add'表示lambda x,y:x + y – waitingkuo

+2

**注意**,reduce已被弃用并在Python 3.x中删除。然后你需要使用[functools.reduce](http://docs.python.org/2/library/functools.html#functools.reduce) – Abhijit

2

它更Python使用chain.from_iterable解开嵌套列表

>>> from itertools import chain 
>>> list(chain.from_iterable(A)) 
[(1, 1), (2, 2), (1, 1), (2, 2), (3, 3), (1, 1)] 
1
import itertools 

a = [[(1, 1), (2, 2)],[(1, 1), (2, 2), (3, 3)], [(1, 1)]] 

list(itertools.chain(*a)) 

退房的itertools module。洛特的好东西。