Python 将random.choice与if语句结合使用
所以我对编程真的很陌生,我昨天刚开始学习Python,我遇到了一点小麻烦。我已经看过了一些教程,还没有想到如何独自回答我的问题,所以我来找你们Python 将random.choice与if语句结合使用,python,Python,所以我对编程真的很陌生,我昨天刚开始学习Python,我遇到了一点小麻烦。我已经看过了一些教程,还没有想到如何独自回答我的问题,所以我来找你们 quickList = ["string1", "string2"] anotherList1 = ["another1a", "another1b"] anotherList2 = ["another2a", "another2b"] for i in range(1): quick=random.choice(quickList)
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,然后再打印另一个1,但是如果quick生成string2,它将打印string2,然后再打印另一个列表2中的条目
有什么提示吗
提前感谢您的帮助 这将对您有用:
quickList = ["string1", "string2"]
anotherList1 = ["another1a", "another1b"]
anotherList2 = ["another2a", "another2b"]
for i in range(1):
if random.choice(quickList) == 'string1':
another1=random.choice(anotherList1)
else:
another2=random.choice(anotherList2)
试着把那个逻辑想清楚。我已为您编排了确切的文字格式:
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
循环中?如果只执行一次,则无需执行此操作。)如果
?如果,会发生什么
quickList = ["string1", "string2"]
anotherList1 = ["another1a", "another1b"]
anotherList2 = ["another2a", "another2b"]
for i in range(1):
quick = random.choice(list(enumerate(quickList)))
anothers = [random.choice(x) for x in (anotherList1, anotherList2)]
print quick[1]
print anothers[quick[0]]
尝试将它们存储在字典中:
d = {
'string1': ['another1a', 'another1b'],
'string2': ['another2a', 'another2b'],
}
choice = random.choice(d.keys())
print choice, random.choice(d[choice])
您的文字与代码不匹配,“string1”是指“另一个1”还是指从另一个列表1中进行选择?如果是后者,我会在数据中明确说明quicks和其他quicks之间的关联:
combinedList = [ ("string1", ["another1a", "another1b"]),
("string2", ["another2a", "another2b"]) ]
quick,anotherList = random.choice( combinedList )
another = random.choice(anotherList)
因为您是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
语句。可以对其进行进一步优化,但请尝试了解此方法:-)