随机选择有效,但有时只有

时间:2013-09-19 14:25:47

标签: python random choice

import random

mylist = ["a", "b", "c"]
mynums = ["1","2","3"]
myint = ["6","7","8"]
random.choice (mylist)

if random.choice(mylist) == "a":
    print ("a")
    random.choice (mynums)
    print (random.choice (mynums))

if random.choice(mylist) == "b":
    print ("b")
    random.choice (myint)
    print (random.choice (myint))

if random.choice(mylist) == "c":
    print ("c")

现在这段代码大部分都有效,但有时候在运行之后;它将在不显示任何内容的情况下执行,或者在同一次运行中选择两个字母。

(我也是python的新手,我对任何让我的上述代码“更整洁/更快”的建议持开放态度。但请解释一下这个变化,我想在改变它之前理解它。)

修改 非常感谢你们!你们都非常乐于助人,我可以加快速度。

3 个答案:

答案 0 :(得分:11)

您在每个if语句中都会收到一个新的随机字母。新选择可能不是您要比较的字母,或者甚至可能是您每次都要比较的字母。没有办法知道。如果你只想从列表中获取一个随机字母,并根据它是哪一个做一些事情,将它存储在一个变量中,然后使用if语句中的变量。

import random

mylist = ["a", "b", "c"]
mynums = ["1","2","3"]
myint = ["6","7","8"]
letterChoice = random.choice(mylist)

if letterChoice == "a":
    print ("a")
    numberChoice = random.choice(mynums)
    print (numberChoice)

if letterChoice == "b":
    print ("b")
    intChoice = random.choice(myint)
    print (intChoice)

if letterChoice == "c":
    print ("c")

答案 1 :(得分:2)

@jonhopkins已经解释了为什么会发生这种情况,但你可以通过将它所引用的字母和列表作为对来使它变得更清晰,然后将代码构造如下:

import random

mynums = ["1","2","3"]
myint = ["6","7","8"]
mylist = (('a', mynums), ('b', myint), ('c', None))

letter, opts = random.choice(mylist)
print letter
if opts:
    print random.choice(opts)

答案 2 :(得分:0)

这可以简化为以下内容。

import random

mylist = ["a", "b", "c"]
mynums = ["1","2","3"]
myint = ["6","7","8"]
letterChoice = random.choice (mylist)
numberChoice = random.choice (mynums)
intchoice = random.choice (myint)

print (letterchoice)
if letterChoice == "a":
    print (numberChoice)
elif letterChoice == "b":
    print (intChoice)