I have created a random list here :
import random
random10 = [random.random() for i in range(50)]
how do i get numbers that smaller thn desired decimal number(like 0.3 / 0.5) and add them to another list ?
CodePudding user response:
Comprehensions can take conditionals for each element.
threshold = 0.3 # or 0.5 or whatever
new_list = [num for num in random10 if num < threshold]
CodePudding user response:
One standard idiom is
def random_in_range(start, end):
rng = end - start
return random.random() * rng start
random10 = [random_in_range(0.3, 0.5) for i in range(10)]
# [0.48723063952147583, 0.326552069793709, 0.36370212050741296, 0.4507434175417475, 0.3836678006116798, 0.3595041921406262, 0.4982543108796589, 0.3617588517560979, 0.3780724902847772, 0.4356521303394746]
which will guarantee a random number in the range you want.
Note that, if you want integers, random.randint()
supports a min and max parameter already, so there's no need to go to this trouble.