[英]Randomly choosing from multiple lists in python
I have 3 lists and want a way that Python chooses multiple options from all lists.我有 3 个列表,希望 Python 从所有列表中选择多个选项。 How can I do this?
我怎样才能做到这一点?
I've tried the code below, but it only gives me 1 option in total.我已经尝试了下面的代码,但它总共只给了我 1 个选项。
list_1 = [1,3,5]
list_2 = [2,4,6]
list_3 = [10]
random.choice([random.choice(list_1)] + [random.choice(list_2)] +
[random.choice(list_3)])
Your question isn't clear but from what I think you are trying to ask:你的问题不清楚,但我认为你想问的是:
To make a random choice from a few lists, you could try this:要从几个列表中随机选择,你可以试试这个:
list_1 = [1,3,5]
list_2 = [2,4,6]
list_3 = [10]
random.choice([random.choice(list_1), random.choice(list_2), random.choice(list_3)])
you can use the random.sample function to retrieve multiple random values您可以使用 random.sample 函数来检索多个随机值
syntax : random.sample(list,k) where k is the number of values to be sampled.语法: random.sample(list,k) 其中 k 是要采样的值的数量。
list_1 = [1,3,5]
list_2 = [2,4,6]
list_3 = [10]
random.sample(list_1+list_2+list_3,3)
[edit] [编辑]
if you want one from each list,如果你想要每个列表中的一个,
final_list = random.sample(list_1,1)+random.sample(list_2,1)+random.sample(list_3,1)
this can be done using random.choice as below这可以使用 random.choice 完成,如下所示
final_list =[ random.choice(list_1),random.choice(list_2),random.choice(list_3)]
Do you mean something like this:你的意思是这样的:
list_1 = [1,3,5]
list_2 = [2,4,6]
list_3 = [10]
[random.choice(list_1)+random.choice(list_2)+random.choice(list_3)]
this would give:这会给:
[1,6,10]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.