I have the following list of strings:
l1 = ['one','two','three']
I want to obtain a list that has, say, these same elements repeated n
times. If n=3
I'd get:
l2 = ['one','one','one','two','two','two','three','three','three']
What I am trying is this:
l2 = [3*i for i in l1]
But what I obtain is this:
l2 = ['oneoneone','twotwotwo','threethreethree']
If I try this:
l2 = [3*(str(i)+",") for i in l1]
I obtain:
l2 = ['one,one,one','two,two,two','three,three,three']
What am I missing?
l2 = [j for i in l1 for j in 3*[i]]
This gives:
['one', 'one', 'one', 'two', 'two', 'two', 'three', 'three', 'three']
This is equivalent to:
l2 = []
for i in l1:
for j in 3*[i]:
l2.append(j)
Note that 3*[i]
creates a list with 3 repeated elements (e.g. ['one', one', 'one']
)
You can use itertools to transform a list of list into a list (in a fast way) :
from itertools import chain
l1 = ['one','two','third']
l2 = list(chain.from_iterable([[e]*3 for e in l1]))
# l2 = ['one','one','one','two','two','two','three','three','three']
so you can define a function that repeat elements like this :
def repeat_elements(l, n)
return list(chain.from_iterable([[e]*n for e in l]))
If you want to use pure list comprehension
[myList[i//n] for i in range(n*len(myList))]
Explanation:
if original list has k elements, repetition factor is n => total number of items in final list: n*k
To map range n*k to k elements, Divide by n. Remember integer divison
You can try to use map
with sum
print(list(sum(map(lambda x: [x] * 3, l1), [])))
Output
['one', 'one', 'one', 'two', 'two', 'two', 'three', 'three', 'three']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With