python中的随机列表选择 [英] Random List choices in python
问题描述
是否可以将变量传递给列表的choice()
函数.我有一堆列表,我想从一个列表中随机选择,然后使用返回的字符串从具有该字符串名称的列表中进行选择.
Is there a way to pass a variable to the choice()
function for a list. I have a bunch of lists and I want to randomly select from one list and then use the string that is returned to select from a list that has that string name.
A = ['1','2','3']
print choice (A) - this gets me a random choice from the list
但是我想将选择存储为变量,并使用它来调用另一个列表
but I want to to store the choice as a variable and use it to call another list
A = ['1','2','3']
1 = ['A','B','C']
Var1 = choice (A)
print choice (Var1) *** this is my problem, how do I pass a variable to the choice function
感谢您的帮助!
推荐答案
在Python中,您可以使用引用.
In Python, you can do this using references.
A = [1, 2, 3]
B = [4, 5, 6]
C = [7, 8, 9]
MasterList = [A, B, C]
whichList = choice(MasterList)
print choice(whichList)
请注意,A, B, C
是先前分配的变量的名称,而不是带引号的字符串.如果您发现自己使用带引号的名称来引用变量,通常可以使用一种更好的方法来完成您要尝试执行的操作.
Note that A, B, C
are names of previously assigned variables, instead of quoted strings. If you ever find yourself using quoted names to refer to variables, there's usually a better way to do whatever you're trying to do.
这篇关于python中的随机列表选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!