import random
string1 = "Fred"
string2 = "Jones"
int1 = 4
int2 = 8
randomInt = random.randint(1, 100)
GloriousListOfFun = [string1, string2, int1, int2, randomInt]
RandomFromGloriousListOfFun = random.choice(GloriousListOfFun)
x=0
while x<1:
line1 = "Hi I am {} from Albion".format(RandomFromGloriousListOfFun)
print(line1)
我知道这是99.9%的没用,但是现在这将返回类似: “嗨,我9岁,来自Albion” “嗨,我9岁,来自Albion” “嗨,我9岁,来自Albion” 等等... 有谁知道我如何让它像这样重复自己,但是每次都有一个随机变量?谢谢。
答案 0 :(得分:1)
您可以使RandomFromGloriousListOfFun
为函数,并在每次迭代时调用它,以便每次它从列表中返回一个随机样本:
GloriousListOfFun = [string1, string2, int1, int2, randomInt]
RandomFromGloriousListOfFun = lambda: random.choice(GloriousListOfFun)
for _ in range(5):
print("Hi I am {} from Albion".format(RandomFromGloriousListOfFun()))
输出
Hi I am 97 from Albion
Hi I am Fred from Albion
Hi I am 8 from Albion
Hi I am Jones from Albion
Hi I am 8 from Albion
答案 1 :(得分:0)
您的错误在这里
RandomFromGloriousListOfFun = random.choice(GloriousListOfFun)
因为它可以使您的随机性得到修复!您应该做的是每次运行random.choice(GloriousListOfFun)
,就像这样:
while x<1:
line1 = "Hi I am {} from Albion".format(random.choice(GloriousListOfFun))
print(line1)
答案 2 :(得分:0)
您可以将这些随机数放入while循环中,以便每次获得新的随机数。
import random
string1 = "Fred"
string2 = "Jones"
int1 = 4
int2 = 8
x=0
while x<1:
randomInt = random.randint(1, 100)
GloriousListOfFun = [string1, string2, int1, int2, randomInt]
RandomFromGloriousListOfFun = random.choice(GloriousListOfFun)
line1 = "Hi I am {} from Albion".format(RandomFromGloriousListOfFun)
print(line1)