File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change
1
+ ```
2
+ 1. random.random()
3
+ random.random()方法返回一个随机数,其在0至1的范围之内,以下是其具体用法:
4
+ import random
5
+ print ("随机数: ", random.random())
6
+ 输出结果:0.22867521257116
7
+
8
+ 2. random.uniform()
9
+ random.uniform()是在指定范围内生成随机数,其有两个参数,一个是范围上限,一个是范围下线,具体用法如下:
10
+ import random
11
+ print (random.uniform(2, 6))
12
+ 输出结果:3.62567571297255
13
+
14
+ 3. random.randint()
15
+ random.randint()是随机生成指定范围内的整数,其有两个参数,一个是范围上限,一个是范围下线,具体用法如下:
16
+ import random
17
+ print (random.randint(6,8))
18
+ 输出结果:8
19
+
20
+ 4. random.randrange()
21
+ random.randrange()是在指定范围内,按指定基数递增的集合中获得一个随机数,有三个参数,前两个参数代表范围上限和下限,第三个参数是递增增量,具体用法如下:
22
+ import random
23
+ print (random.randrange(6, 28, 3))
24
+ 输出结果:15
25
+
26
+ 5. random.choice()
27
+ random.choice()是从序列中获取一个随机元素,具体用法如下:
28
+ import random
29
+ print (random.choice("www.jb51.net"))
30
+ 输出结果:w
31
+
32
+ 6. random.shuffle()
33
+ random.shuffle()函数是将一个列表中的元素打乱,随机排序,具体用法如下:
34
+ import random
35
+ num = [1, 2, 3, 4, 5]
36
+ random.shuffle(num)
37
+ print (num)
38
+ 输出结果:[3, 5, 2, 4, 1]
39
+
40
+ 7. random.sample()
41
+ random.sample()函数是从指定序列中随机获取指定长度的片段,原有序列不会改变,有两个参数,第一个参数代表指定序列,第二个参数是需获取的片段长度,具体用法如下:
42
+ import random
43
+ num = [1, 2, 3, 4, 5]
44
+ sli = random.sample(num, 3)
45
+ print (sli)
46
+ 输出结果:[2, 4, 5]
47
+ ```
You can’t perform that action at this time.
0 commit comments