python从两个列表中随机组合值

时间:2017-05-24 19:00:54

标签: python random

我有三个值列表(数字和字母),我想编写一个程序,使每个列表中的一个随机组合。

我找到了一个代码,制作了所有可能的值组合,我认为这可能是一个很好的基础,但现在我不知道如何继续。谁能帮帮我?

这里是我的代码

import itertools

square = [a, s, d, f, g, h, j, k, l ]
circle = [w, e, r, t, z, u, i, o, p ]
line = [y, x, c, v, b, n, m ]
radiusshape = [1, 2, 3, 4, 5, 6, 7, 8, 9 ]

for L in range(0, len(stuff)+1):
  for subset in itertools.combinations(stuff, L):
    print(subset)

2 个答案:

答案 0 :(得分:3)

您可以使用random.sample从生成的cartesian product

中抽取k个随机样本
# where k is number of samples to generate
samples = random.sample(itertools.product(square, circle, line, radiusshape), k)

例如

>>> a = [1, 2, 3, 4]
>>> b = ['a', 'b', 'c', 'd']
>>> c = ['foo', 'bar']
>>> random.sample(set(itertools.product(a,b,c)), 5)
[(1, 'c', 'foo'),
 (4, 'c', 'bar'),
 (1, 'd', 'bar'),
 (2, 'a', 'foo'),
 (2, 'd', 'foo')]

答案 1 :(得分:0)

您可以使用random.choice()函数从列表中选择随机元素,因此只需在所有4个列表中使用它:

from random import choice

combination = (choice(square), choice(circle), choice(line), choice(radiusshape))
相关问题