How to repeat the numbers in a list in python?

Viewed 588

I have a list

 A = [1,6,3,8,5,5,2,1,2,10]

I want to repeat the numbers in this like:

A = [1,6,6,6,6,6,6,3,3,3,8,8,8,8,8,8,8,8,..... so on] 

i.e 1 repeat once, 6 repeat six times, 3 repeat thrice and so on....

I tried with:

B=np.concatenate([([x]*x) for x in A], axis=0) 

but it multiplying the corresponding number and I am getting this result:

  B = [1,36,36,36,36,36,36,9,9,9,.....so on]

when I am doing:

B=np.concatenate([([x]*3) for x in A], axis=0)

this giving me:

B = [1,1,6,6,3,3,8,8... so on]

what wrong I am doing here?

7 Answers

You can perform this operation using numpy without using a for loop.

np.repeat(a, repeats) will repeat the input array a according to repeats which specify the number of repetitions for each element.

import numpy as np
A = [1,6,3,8,5,5,2,1,2,10]
B = np.repeat(A,A)

Output:

>>> array([ 1,  6,  6,  6,  6,  6,  6,  3,  3,  3,  8,  8,  8,  8,  8,  8,  8,
    8,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  2,  2,  1,  2,  2, 10,
   10, 10, 10, 10, 10, 10, 10, 10, 10])

Using the repeat function of NumPy you can get the solution

import numpy as np
np.repeat(A, A)

You should use nested loop

l  = [1, 6, 3]
nl = []
for number in l:
    for i in range(number):
        nl.append(number)
print(nl)

or using list comprehension

l = [1,6,3]
nl = [number  for number in l for i in range(number)]
#[1, 6, 6, 6, 6, 6, 6, 3, 3, 3] 

hello you can make this with the lib itertools:

import itertools
lst = [1,2,3,4,5]
# [1, 2, 3, 4, 5]
list(itertools.chain.from_iterable(itertools.repeat(x, x) for x in lst)) 
#[1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5]

You have a list of integers, to which the multiplication means arithmetic multiplication. You need to convert them into strings.

A = [1,6,3,8,5,5,2,1,2,10]
new_A = [x * str(x) for x in A]

which is called list comprehension, being a much cleaner/pythonic way of:

for x in A:
new_A.append(x * str(x))
B = np.concatenate([[a]*a for a in A])

>>> array([ 1,  6,  6,  6,  6,  6,  6,  3,  3,  3,  8,  8,  8,  8,  8,  8,  8,
    8,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  2,  2,  1,  2,  2, 10,
   10, 10, 10, 10, 10, 10, 10, 10, 10])
nums = [1, 5, 4]
res = []
for num in nums:
    res.extend([num] * num)
print(res)
# [1, 5, 5, 5, 5, 5, 4, 4, 4, 4]
Related