Python中random用法
时间: 2024-02-16 17:29:48 浏览: 33
Python中的`random`模块提供了生成随机数的函数。下面是几个常用的函数和用法:
1. `random.random()`:生成一个0到1之间的随机浮点数。
```python
import random
print(random.random())
```
2. `random.randint(a, b)`:生成一个a到b之间的随机整数(包括a和b)。
```python
import random
print(random.randint(1, 10))
```
3. `random.choice(seq)`:从序列seq中随机选择一个元素。
```python
import random
seq = ['apple', 'banana', 'cherry']
print(random.choice(seq))
```
4. `random.shuffle(seq)`:将序列seq中的元素随机排序。
```python
import random
seq = [1, 2, 3, 4, 5]
random.shuffle(seq)
print(seq)
```
5. `random.sample(population, k)`:从population序列中随机选择k个元素,返回一个新的序列。
```python
import random
population = ['apple', 'banana', 'cherry', 'date', 'elderberry']
print(random.sample(population, 3))
```
相关问题
python中random用法
在Python中,random模块可以帮助程序生成随机数。常用的函数有:
1. random():返回0-1之间的随机小数。
2. randint(a, b):返回[a, b]之间的整数。
3. uniform(a, b):返回[a, b]之间的随机小数。
4. choice(seq):返回序列seq中的一个随机元素。
5. shuffle(seq):将序列seq中的元素随机排序。
6. sample(seq, n):从序列seq中随机选取n个元素,返回一个列表。
需要注意的是,在使用这些函数前需要import random模块。
python中random函数用法
在Python中,random模块提供了生成随机数的函数。其中常用的函数有:
1. random.random():生成一个[0, 1)范围内的随机浮点数。
2. random.randint(a, b):生成一个[a, b]范围内的随机整数。
3. random.choice(seq):从序列seq中随机选择一个元素。
4. random.shuffle(seq):将序列seq中的元素随机打乱。
5. random.sample(population, k):从序列population中随机选择k个元素,返回一个新列表。
以下是一些示例代码:
```python
import random
# 生成随机浮点数
print(random.random())
# 生成随机整数
print(random.randint(1, 10))
# 从序列中随机选择元素
colors = ['red', 'blue', 'green']
print(random.choice(colors))
# 打乱序列
numbers = [1, 2, 3, 4, 5]
random.shuffle(numbers)
print(numbers)
# 从序列中选择多个元素
cards = ['A', '2', '3', '4', '5']
hand = random.sample(cards, 3)
print(hand)
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)