I would like to create a generator of random numbers.
import numpy as np
rd_list = (np.random.randint(10) for i in range(6))
When I try with this I get values [7, 1, 4, 2, 0, 6].
I would like to filter these results by this condition < 5.
How can I get this result?
CodePudding user response:
One approach is to wrap the random generator in a user-defined function, which will give you control over the starting and ending numbers, as well as the number of values to generate.
Edit: Updated to address the requirement for random length lists, via filtering to a minimum value.
Example:
import random
def randgen(start: int, stop: int, n: int, min_: int):
"""Return a generator of random integers.
Args:
start (int): Starting integer.
stop (int): Ending integer, inclusive.
n (int): Number of values to generate.
min_ (int): Minimum value to include, inclusive.
"""
return (random.randint(start, stop) for i in range(n) if i <= min_)
Output:
>>> list(randgen(0, 5, 10, 3))
[3, 4, 0, 2]
CodePudding user response:
Another way using assignment expression (Python 3.8 ):
import random
nums = (n for _ in range(6) if (n := random.randint(0, 10)) < 5)
Thanks to Andrej's comment: Since you are already using numpy
, you don't need the loop:
import numpy as np
nums = (n for n in np.random.randint(0, 10, 6) if n < 5)
CodePudding user response:
`for i in range(6):
a=np.random.randint(10)
If(a<5):
List.append(a)`