list.extend和list comprehension

时间:2010-10-10 08:49:38

标签: python list list-comprehension

当我需要在列表中添加几个相同的项目时,我使用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']

有什么想法吗?

6 个答案:

答案 0 :(得分:32)

Stacked LCs。

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

答案 1 :(得分:5)

>>> a = [['a',2], ['b',2], ['c',1]]
>>> [i for i, n in a for k in range(n)]
['a', 'a', 'b', 'b', 'c']

答案 2 :(得分:5)

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']

答案 3 :(得分:3)

如果您更喜欢扩展列表推导:

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

答案 4 :(得分:1)

import operator
a = [['a',2], ['b',2], ['c',1]]
nums = [[x[0]]*x[1] for x in a]
nums = reduce(operator.add, nums)

答案 5 :(得分:1)

>>> a = [['a',2], ['b',2], ['c',1]]
>>> sum([[item]*count for item,count in a],[])
['a', 'a', 'b', 'b', 'c']