简体   繁体   中英

How can I generate random numbers and assign them to variables in python?

Suppose I want the variables a_1, a_2, a_3, a_4 to be random numbers from the uniform distribution U(0,100). I could write

import random

a_1 = random.uniform(0,100) 
a_2 = random.uniform(0,100) 
a_3 = random.uniform(0,100)
a_4 = random.uniform(0,100)

But I was wondering if there is a more efficient way to do this. I tried the following,

import random

for i in range(4):
    a_i = random.uniform(1,100)
    print(a_i)

However, this did not work. For example, when I call a_1 later on, it says a_1 is not defined. How can I fix this?

Put the random values into a list and then access members by index:

>>> import random
>>> a = [random.uniform(1,100) for _ in range(4)]
>>> a
[71.4615087249735, 19.04308860149112, 40.278774122696014, 69.18947997939686]
>>> a[0]
71.4615087249735
>>> a[2]
40.278774122696014

Unless you have a really, really good reason, defining variables dynamically is kind of hard to justify.

If you do not wish to use a list, you can use the unpack functionality

import random
up, down, strange, charm = [random.uniform(1,100) for _ in range(4)]

it seems You need numbers in range(0,100), well if you wanna generate random integer within a range(or other iterable) try this. just in case you need it to be more specific

import random numberOf_intRequired=4 random_int=random.sample(range(0,100),numberOf_intRequired)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM