从python中的多个列表中随机选择

茉莉花

我有3个列表,并希望Python从所有列表中选择多个选项。我怎样才能做到这一点?

我已经尝试了下面的代码,但总共只给了我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)])
文卡塔克里希南

您可以使用random.sample函数检索多个随机值

语法: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)

[编辑]

如果您想从每个列表中选择一个,

final_list = random.sample(list_1,1)+random.sample(list_2,1)+random.sample(list_3,1)

可以使用random.choice如下所示

final_list =[ random.choice(list_1),random.choice(list_2),random.choice(list_3)]

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章