2010-10-10 68 views
19

當我需要幾個相同的項目添加到我使用list.extend名單:list.extend和列表理解

a = ['a', 'b', 'c'] 
a.extend(['d']*3) 

結果

['a', 'b', 'c', 'd', 'd', 'd'] 

但是,如何做列表相似理解?

a = [['a',2], ['b',2], ['c',1]] 
[[x[0]]*x[1] for x in a] 

結果

[['a', 'a'], ['b', 'b'], ['c']] 

但我需要這一個

['a', 'a', 'b', 'b', 'c'] 

任何想法?

回答

23

堆積的液相色譜。

[y for x in a for y in [x[0]] * x[1]] 
+5

謝謝!它的作品,但我甚至不知道如何閱讀這個表達。 – Stas 2010-10-10 08:58:29

+0

'for a中的x'每次將'a'的每個元素提取爲'x'。 '...中的y'從'x'創建一個新列表,並將其元素一次一個地提取到'y'中。這一切都發生在同一時間(或多或少),導致它們都處於相同的嵌套層次。 – 2010-10-10 09:00:56

+9

它通常在解包時更加清楚:[y for(item,times)in y in [item] * times] – tokland 2010-10-10 09:05:00

4
>>> a = [['a',2], ['b',2], ['c',1]] 
>>> [i for i, n in a for k in range(n)] 
['a', 'a', 'b', 'b', 'c'] 
1
import operator 
a = [['a',2], ['b',2], ['c',1]] 
nums = [[x[0]]*x[1] for x in a] 
nums = reduce(operator.add, nums) 
+2

'reduce(operator.add,...)'是O(n^2)。 – kennytm 2010-10-10 09:05:35

3

itertools方法:

import itertools 

def flatten(it): 
    return itertools.chain.from_iterable(it) 

pairs = [['a',2], ['b',2], ['c',1]] 
flatten(itertools.repeat(item, times) for (item, times) in pairs) 
# ['a', 'a', 'b', 'b', 'c'] 
1
>>> a = [['a',2], ['b',2], ['c',1]] 
>>> sum([[item]*count for item,count in a],[]) 
['a', 'a', 'b', 'b', 'c'] 
2

如果你更喜歡在擴展列表解析:

a = [] 
for x, y in l: 
    a.extend([x]*y)