3

I have three lists of values (numbers and letters) and I want to write a program that makes combinations of one of each lists randomly.

I found a code making all possible combinations of values and I thought that might be a good base, but now I don t know how to continue. Who can help me?

Here the code I have

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)
4
  • can you please write desire output ? which kind of combination pair you need as output. single/multiple from two list or from all, within list or from any list. please specify Commented May 24, 2017 at 19:04
  • I want combinations that include one value of each list. for example "awy1" or "stb8" Commented May 24, 2017 at 19:07
  • then you already got solution from @Martin Broadhurst Commented May 24, 2017 at 19:10
  • fwiw you are looking for sampling out of a "cartesian product" not a set of "combinations" Commented May 24, 2017 at 19:13

2 Answers 2

10

You can use random.sample to draw k random samples from your generated cartesian product

# where k is number of samples to generate
samples = random.sample(itertools.product(square, circle, line, radiusshape), k)

For example

>>> 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')]
Sign up to request clarification or add additional context in comments.

Comments

1

You can use the random.choice() function to select a random element from a list, so just use it on all 4 lists:

from random import choice

combination = (choice(square), choice(circle), choice(line), choice(radiusshape))

2 Comments

great! it works. Is there a way how I can tell it to do X amount of combinations at once?
Just use a for loop over range(), but I think CoryKramer's solution is better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.