2
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 新手,我愿意接受任何让我的上述代码“更整洁/更快”的建议。但请解释一下更改,我想在更改之前了解它。)

编辑 非常感谢大家!你们都非常有帮助,我可能会补充说很快。

4

3 回答 3

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")
于 2013-09-19T14:30:54.940 回答
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)
于 2013-09-19T14:38:10.857 回答
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)
于 2013-09-19T14:40:31.373 回答