首页 > 解决方案 > Python random.choice 相同的输出

问题描述

我正在尝试随机变量中的一些字符串,

myTest = random.choice(["test1","test2","test3"])
print(myTest)
print(myTets)
print(myTest)

当我运行我的脚本时,它们每次都是一样的,

test1
test1
test1

我喜欢在每次调用它时随机化我的变量,比如,

test1
test3
test2

标签: pythonpython-3.xrandom

解决方案


这与基本相同

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)

推荐阅读