Python () range with duplicates?

So everyone knows that I can get a list of numbers with range as follows:

 >>> range(5) [0, 1, 2, 3, 4] 

And if I want, say, 3 copies of each number that I could use:

 >>> range(5)*3 [0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4] 

But is there a way to use range to repeat copies like this?

 [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4] 

Is there a quick and elegant built-in way to do this? sorted(range(5)*3) has unnecessary complexity n * log (n), and [x//3 for x in range(3*5)] works, but looks like an abuse of the // operation.

+4
source share
7 answers

You can do:

 >>> [i for i in range(5) for _ in range(3)] [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4] 

the range(3) should be replaced by your number of repetitions ...

By the way, you should use generators


To make it understandable, _ is the name of the variable for something you don't need about (any name is allowed).

In this understanding of lists, nested for loops are used and are the same:

 for i in range(5): for j in range(3): #your code here 
+11
source

Try the following:

 itertools.chain.from_iterable(itertools.repeat(x, 3) for x in range(5)) 
+7
source
 from itertools import chain, izip list(chain(*izip(*[xrange(5)]*3))) 

gives

 [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4] 

Leave the list and you have a generator.

EDIT: or even better (excludes function call for izip):

 list(chain(*([x]*3 for x in xrange(5)))) 
+4
source
 >>> from itertools import chain, izip, tee >>> list(chain.from_iterable(izip(*tee(range(5), 3)))) [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4] 
+1
source

Cool iterator using a different approach:

 >>> from collections import Counter >>> Counter(range(5) * 3).elements() 
+1
source
 import itertools [x for tupl in itertools.izip(*itertools.tee(range(0,5),3)) for x in tupl] 

Or:

 [x for tupl in zip(range(0,5), range(0,5), range(0,5)) for x in tupl] 
-2
source

I like to keep it simple :)

 >>> sorted(list(range(5)) * 3) [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4] 
-2
source

Source: https://habr.com/ru/post/1368897/


All Articles