JPC
JPC

Reputation: 5173

python list comprehension to create repeated value from the list

I am trying to create

[ x 
 for x in [1,2,3] 
     for y in [3,1,4] ]

Output:

[1, 1, 1, 2, 2, 2, 3, 3, 3]

but what I want is to create

Expected Output:

[1, 1, 1, 2, 3, 3, 3, 3]

Is it possible to do this in list comprehension ?

Upvotes: 0

Views: 109

Answers (3)

David Arenburg
David Arenburg

Reputation: 92282

I'm you could also use np.repeat if you fine with an array as a results

import numpy as np
np.repeat([1, 2, 3] ,[3, 1, 4])

Upvotes: 1

TigerhawkT3
TigerhawkT3

Reputation: 49320

Sure, with zip:

>>> [item for x,y in zip([1,2,3], [3,1,4]) for item in [x]*y]
[1, 1, 1, 2, 3, 3, 3, 3]

Upvotes: 2

Martijn Pieters
Martijn Pieters

Reputation: 1121206

Use the zip() function to pair up your numbers with their counts:

numbers = [1, 2, 3]
counts = [3, 1, 4]
output = [n for n, c in zip(numbers, counts) for _ in range(c)]

Upvotes: 5

Related Questions