python 实现随机值 源代码
时间: 2024-01-30 10:03:29 浏览: 18
当然,我可以帮您回答这个问题。Python中生成随机值的方法比较多,这里给您列举两种常用的方法。第一种是使用Python内置的random库,通过random模块中的randint函数生成指定范围内的随机整数。比如,生成1到100之间的随机整数,可以使用以下代码:
```python
import random
random_num = random.randint(1, 100)
print(random_num)
```
第二种方法是使用Numpy库,该库可以生成各种分布的随机数,比如正态分布、均匀分布等。生成numpy库中的随机数需要先安装Numpy库。例如,生成一个均匀分布的随机数组:
```python
import numpy as np
random_array = np.random.random((3,2))
print(random_array)
```
希望这个回答能够帮到您!
相关问题
python 实现随机读写文本文件 源代码
可以使用以下代码实现:
```python
import random
with open('file.txt', 'r') as f:
lines = f.readlines()
with open('file.txt', 'w') as f:
for i in range(len(lines)):
line = random.choice(lines)
f.write(line)
lines.remove(line)
```
以上代码会将文件中的每一行随机打乱并重新写入文件中。
python 实现文件加密 源代码
可以使用 cryptography 库中的 Fernet 对称加密算法来实现文件的加密。以下是一个示例代码:
```python
from cryptography.fernet import Fernet
# 生成一个加密密钥
key = Fernet.generate_key()
# 将密钥保存到文件中
with open('key.txt', 'wb') as f:
f.write(key)
# 加载密钥
with open('key.txt', 'rb') as f:
key = f.read()
# 创建一个 Fernet 对象
f = Fernet(key)
# 加密文件
with open('plaintext.txt', 'rb') as plaintext:
with open('ciphertext.txt', 'wb') as ciphertext:
ciphertext.write(f.encrypt(plaintext.read()))
# 解密文件
with open('ciphertext.txt', 'rb') as ciphertext:
with open('decrypted.txt', 'wb') as plaintext:
plaintext.write(f.decrypt(ciphertext.read()))
```
这段代码将生成一个随机的密钥,并将密钥保存到文件中。然后可以使用该密钥来加密和解密文件。注意,密钥的保护非常重要,因为如果密钥泄露,加密的文件可以被解密。