在if语句中使用random.choice

1 投票
6 回答
1012 浏览
提问于 2025-04-16 01:15

我刚开始学习编程,昨天才开始学Python,现在遇到了一些问题。看了几个教程,但还是没能自己找到答案,所以我来请教大家。

quickList = ["string1", "string2"]
anotherList1 = ["another1a", "another1b"]
anotherList2 = ["another2a", "another2b"]

for i in range(1):
    quick=random.choice(quickList)
    another1=random.choice(anotherList1)
    another2=random.choice(anotherList2)

我想写一段代码,如果quick生成了string1,就打印string1,然后再打印another1;如果quick生成了string2,就打印string2,然后从anotherList2中随机打印一个。

有没有什么提示呢?

提前谢谢大家的帮助!

6 个回答

1

试着理清这个逻辑。我把你的话整理了一下:

if (quick turns up string1):
    print string1
    print another1 //I assume you mean a string from this list
but if (quick generates string2):
    print string2 
    and then an entry from anotherList2

这就是你想要的逻辑,现在你只需要把它翻译回Python代码就可以了。我就不帮你做这部分了。

一般来说,试着把if语句和逻辑中的具体选择联系起来。这会帮助你用任何语言写代码。

(顺便问一下,为什么要放在for循环里?如果只做一次的话其实没必要。)

2

试着把它们存放在一个字典里:

d = {
    'string1': ['another1a', 'another1b'],
    'string2': ['another2a', 'another2b'],
}
choice = random.choice(d.keys())
print choice, random.choice(d[choice])
0

既然你刚接触Python,我来给你推荐另一种做法。

quickList = ["string1", "string2"]
anotherList = {"string1": ["another1a", "another1b"],
               "string2": ["another2a", "another2b"]}

for i in range(1):
    quick = random.choice(quickList)
    print quick
    print random.choice(anotherList[quick])

还有其他人提到的,我不太明白你为什么要把代码放在一个for循环里。其实你可以把它去掉,不过我这次示例里还是保留了。

这样做可以让你更方便地扩展你的列表,也能省去写很多if语句的麻烦。这个方法可以进一步优化,但你可以先试试看,看看你是否能理解这种做法 :-)

撰写回答