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

2024-03-28 14:08:10 发布

您现在位置:Python中文网/ 问答频道 /正文

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

编辑 非常感谢大家!你们都帮了大忙,我可以补充一句。你知道吗


Tags: 代码import编辑内容if字母random建议
3条回答

这可以简化为以下内容。你知道吗

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)

@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)

在每个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")

相关问题 更多 >