list.extend and list comprehension

2019-01-18 18:21发布

When I need to add several identical items to the list I use list.extend:

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

Result

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

But, how to do the similar with list comprehension?

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

Result

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

But I need this one

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

Any ideas?

6条回答
Evening l夕情丶
2楼-- · 2019-01-18 18:29
>>> a = [['a',2], ['b',2], ['c',1]]
>>> sum([[item]*count for item,count in a],[])
['a', 'a', 'b', 'b', 'c']
查看更多
相关推荐>>
3楼-- · 2019-01-18 18:35

Stacked LCs.

[y for x in a for y in [x[0]] * x[1]]
查看更多
Ridiculous、
4楼-- · 2019-01-18 18:38

If you prefer extend over list comprehensions:

a = []
for x, y in l:
    a.extend([x]*y)
查看更多
相关推荐>>
5楼-- · 2019-01-18 18:38
import operator
a = [['a',2], ['b',2], ['c',1]]
nums = [[x[0]]*x[1] for x in a]
nums = reduce(operator.add, nums)
查看更多
爷、活的狠高调
6楼-- · 2019-01-18 18:48
>>> a = [['a',2], ['b',2], ['c',1]]
>>> [i for i, n in a for k in range(n)]
['a', 'a', 'b', 'b', 'c']
查看更多
Bombasti
7楼-- · 2019-01-18 18:52

An itertools approach:

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']
查看更多
登录 后发表回答