保存随机选择并在以后使用它

时间:2014-01-22 18:51:03

标签: python random

我有我的程序从列表中选择一个随机选择:

from random import choice
solider_long = ['1', '2', '3']
from random import choice
solider_speed = [ '4', '5', '6']
from random import choice 
solider_block = [ '4', '5', '6']          
print ("You choose solider")
print ("Your stats: close combat : " + choice(solider_close))
print ("            long range combat : " + choice(solider_long))
print ("            long range combat : " + choice(solider_speed))
print ("            long range combat : " + choice(solider_block))
print ("Press Y to continue")

我希望程序记住它是随机选择,所以我可以在程序中使用它后面选择的数字。怎么办呢?

2 个答案:

答案 0 :(得分:2)

您只需要导入一次。您可以将choice()保存到稍后可以使用的变量中。

from random import choice


solider_long = ['1', '2', '3']

solider_speed = [ '4', '5', '6']

solider_block = [ '4', '5', '6']

# save the choices in a variable
choice_solider_close = choice(solider_close)
choice_solider_long = choice(solider_long)
choice_solider_speed = choice(solider_speed)
choice_solider_block = choice(solider_block)

print ("You choose solider")
print ("Your stats: close combat : " + choice_solider_close)
print ("            long range combat : " + choice_solider_long)
print ("            long range combat : " + choice_solider_speed)
print ("            long range combat : " + choice_solider_block)
print ("Press Y to continue")

答案 1 :(得分:1)

你在第一个之后的进口没有任何意义,摆脱它们。

完成后,解决方案很简单:

c1 = choice(soldier_close)
c2 = choice(soldier_long)
c3 = choice(soldier_speed)
c4 = choice(soldier_block)

如果您不熟悉变量的概念,请考虑阅读Python教程,例如官方的:http://docs.python.org/2/tutorial/