Python repeats a single value with repeat()

Python Repeating a Single Value with repeat() The function repeat() seems a bit strange: it repeatedly returns a single value. It can be used instead of the cycle() function when a single value is needed.

The difference between selecting all data and selecting part of the data is that the expression (x==0 for x in cycle(range(size))) generates the sequence [True, False, False, ...], which is used to select part of the data; the expression (x==0 for x in repeat(0)) generates the sequence [True, True, True, ...], which is used to select all the data.

Consider the following code:

all = repeat(0)
subset = cycle(range(100))
choose = lambda rule: (x == 0 for x in rule)
# choose(all) or choose(subset) can be used

You can switch between selecting all data or part of the data by simply changing the parameters. This method can be extended to randomly select a data set as follows:

def randseq(limit):
while True:
yield random.randrange(limit)
randomized = randseq(100)

randseq() function generates an infinitely long sequence of random numbers within a specified range, enriching the two selection modes of cycle() and repeat().

The implementation of different picking methods is as follows:

[v for v, pick in zip(data, choose(all)) if pick]
[v for v, pick in zip(data, choose(subset)) if pick]
[v for v, pick in zip(data, choose(randomized)) if pick]

Using chose(all), chose(subset), or chose(randomized) can conveniently provide input data for subsequent analysis.

Leave a Reply

Your email address will not be published. Required fields are marked *