Python random.choice相同的输出

Python random.choice相同的输出,python,python-3.x,random,Python,Python 3.x,Random,我试图在一个变量中随机选取一些字符串 myTest = random.choice(["test1","test2","test3"]) print(myTest) print(myTets) print(myTest) 当我运行我的脚本时,它们每次都是一样的 test1 test1 test1 每次调用变量时,我都喜欢随机调用它,比如 test1 test3 test2 每次都必须调用该命令: myTest = random.choice(["test1","test2","test3"

我试图在一个变量中随机选取一些字符串

myTest = random.choice(["test1","test2","test3"])
print(myTest)
print(myTets)
print(myTest)
当我运行我的脚本时,它们每次都是一样的

test1
test1
test1
每次调用变量时,我都喜欢随机调用它,比如

test1
test3
test2

每次都必须调用该命令:

myTest = random.choice(["test1","test2","test3"])
print(myTest)
myTest = random.choice(["test1","test2","test3"])
print(myTest)
myTest = random.choice(["test1","test2","test3"])
print(myTest)
试试这个

print(random.choice("test1","test2","test3"))
print(random.choice("test1","test2","test3"))
print(random.choice("test1","test2","test3"))
请访问。在您的情况下,可以如下所示:

import random
my_tests = ['test1','test2','test3']
for choice in random.sample(my_tests, 3):
    print(choice)
import random
myTest = random.choice(["test1, test2, test3"])
print(myTest)
另一种选择是就地执行,换句话说,通过更改
my_tests

import random
my_tests = ['test1','test2','test3']
print(my_tests, '\n\n')
for i in range(10):
    random.shuffle(my_tests)
    print(my_tests)

这基本上与

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)

首先,您必须导入随机变量。然后您应该将test1、test2和test3放在一个字符串中。然后你可以得到你想要的结果,如下所示:

import random
my_tests = ['test1','test2','test3']
for choice in random.sample(my_tests, 3):
    print(choice)
import random
myTest = random.choice(["test1, test2, test3"])
print(myTest)

如果您想将结果存储在某个地方而不是仅仅打印,您应该只使用,这些值将直接存储在一个新的列表中

口译员:

>>> import random
>>>
>>> choices = ["test1","test2","test3"]
>>> selected = [random.choice(choices) for _ in range(3)] # iterates 3 times, appending value of "random.choice(choices)" to the end of the list
>>> print(selected)
['test1', 'test2', 'test2']
顺便说一下,“u”只是一个“我不在乎”变量,用于存储不需要的值,如果需要数字,可以将其命名为一个合适的变量,如“I”,然后使用它


编辑:同样,在回答您的问题后,请选择帮助您解决问题的答案。谢谢。

myTets
是打字错误吗?另外,
random.choice
不是可变的,它只需要一个参数(应该是一个列表):
random.choice([“test1”、“test2”、“test3”])
因此,每次需要随机字符串时,您都必须调用random。相关:您重复打印变量的值,而不更改它。让我明确一点,我有一个var.py,我正在保存变量,而在另一个python文件中,我正试图读取var。myTest@ArmanTrb我不明白这和你的工作有什么关系问题。@ArmanTrb如果您不能将我的答案直接用于您的问题,您应该编辑您的问题,以显示一个更复杂的示例,说明您所做的事情,并更详细地解释您正在尝试做的事情。@ArmanTrb如果您想更改
var.myTest
的值,则必须为其指定不同的值。如果只指定一次,则它永远不会更改。在
var.py
中使用全局变量似乎是解决实际问题的错误方法。我建议您学习函数以及如何向函数传递参数。@ArmanTrb如果您有上千个这样的变量,这并不重要。你对这些变量做什么也无关紧要。您必须调用
random。每次要选择一个随机元素时,请选择
。这是没有办法的。但是,您可以编写一个函数,如
def random\u greeting():return random.choice(['Hi','Greetings','Welcome'])
,然后只要在需要随机问候语时调用该函数即可:
print(random\u greeting())
。但这不会重复值,因此它与在循环中调用
choice
不同。当然,OP可能真的想要这样。如果他们这样做了,另一个选择是调用列表上的
shuffle
,如果您不介意对原始列表进行无序排列的话。