sirve que para python list list-comprehension

python - que - list.extend y lista de comprensión



python extend expand (6)

LCs apilados.

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

Cuando necesito agregar varios elementos idénticos a la lista, uso list.extend:

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

Resultado

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

Pero, ¿cómo hacer lo similar con la lista de comprensión?

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

Resultado

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

Pero necesito este

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

¿Algunas ideas?


Si prefieres ampliar sobre las comprensiones de la lista:

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


Un enfoque de 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'']


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


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


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