在Python中,您可以使用`random`模块来生成随机数。以下是一些基本用法:
1. 生成随机整数:
```python
import random
num = random.randint(a, b) a是范围的下限,b是范围的上限
print(num)
2. 生成随机浮点数:
```python
import random
float_num = random.random() 生成0到1之间的随机浮点数
print(float_num)
3. 从序列中随机选择元素:
```python
import random
fruits = ['苹果', '香蕉', '橙子', '葡萄']
fruit = random.choice(fruits)
print(f'今天吃{fruit}')
4. 打乱列表顺序:
```python
import random
numbers = list(range(1, 11))
random.shuffle(numbers)
print(numbers)
5. 生成指定范围的随机浮点数:
```python
import random
price = random.uniform(a, b) a是范围的下限,b是范围的上限
print(price)
6. 随机抽取多个元素:
```python
import random
cards = list(range(1, 55))
hands = random.sample(cards, k=5) k是要抽取的元素数量
print(hands)
7. 按权重随机选择:
```python
import random
choices = ['金币', '钻石', '道具']
weights = [60, 30, 10] 权重列表
k = 3 抽取次数
choices_weighted = random.choices(choices, weights=weights, k=k)
print(choices_weighted)
您可以根据需要选择合适的方法来生成随机数