python - Python random.choice 相同的输出
问题描述
我正在尝试随机变量中的一些字符串,
myTest = random.choice(["test1","test2","test3"])
print(myTest)
print(myTets)
print(myTest)
当我运行我的脚本时,它们每次都是一样的,
test1
test1
test1
我喜欢在每次调用它时随机化我的变量,比如,
test1
test3
test2
解决方案
这与基本相同
x = 42
print(x)
print(x)
print(x)
变量值仅在您分配时更改:
x = 42
print(x)
x = 45
print(x)
如果你想要一个新的随机值,你需要再次调用该函数:
l = [1, 2, 3, 4, 5]
x = random.choice(l)
print(x)
x = random.choice(l)
print(x)
推荐阅读
- docker - 在 Docker 场景中将 `/var/run/docker.sock` 挂载到 Docker 中的结果是什么?
- java - 按钮不在我告诉他们的地方
- python - 带有 Django 的 Python API
- xamarin.forms - 来自 URL 的 Skiasharp 贷款图像并在 Xamarin 表单中的 Canvas 上绘制
- rust - 如何让 Serde 结构同时处理借用和拥有的数据?
- nginx - 带有 URL 重写的代理后面的 NextJS
- solidity - 合约的方法返回空对象
- ipfs - 如何使用 IPFS-JS 获取公共 IP 地址
- c - 如何重置全局变量prev?
- php - 开发奖励盒算法