Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: expand list of strings by adding n elements for each original element [duplicate]

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?

like image 775
Zizzipupp Avatar asked Jun 29 '20 13:06

Zizzipupp


4 Answers

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

like image 102
Aziz Avatar answered Oct 21 '22 13:10

Aziz


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]))
like image 5
H4kim Avatar answered Oct 21 '22 13:10

H4kim


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

like image 5
Holy_diver Avatar answered Oct 21 '22 14:10

Holy_diver


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']
like image 3
Leo Arad Avatar answered Oct 21 '22 13:10

Leo Arad