开发者

list.extend and list comprehension [duplicate]

开发者 https://www.devze.com 2023-01-19 15:08 出处:网络
This question already has answers here: 开发者_开发技巧How can I get a flat result from a list comprehension instead of a nested list?
This question already has answers here: 开发者_开发技巧 How can I get a flat result from a list comprehension instead of a nested list? (13 answers) Closed 4 months ago.

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?


Stacked LCs.

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


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


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


If you prefer extend over list comprehensions:

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


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


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

精彩评论

暂无评论...
验证码 换一张
取 消