简体   繁体   中英

How to make itertools.product() random

I have the code below that will print all possible combination of 'abc'. Is there a way I can only print part of the combinations, or to make it print the combination randomly every time.

my code is:

from itertools import product
for item in product('abc', repeat=3):
  codes = (''.join(item))
  print(codes)

the result with this code gives me this:

aaa
aab
aac
aba
abb
abc
.
.
.
bcc
caa
cca
ccb
ccc

I want it the result to be random everytime or only print specific part like this:

bcc
caa
cca
ccb
ccc

I'd probably use something like:

from itertools import product
from random import choice

all_samples = ["".join(x) for x in product("abc", repeat=3)][0:10] # as requested on the comments, limits the list to the first 10 items.

def rand_sample():
    sample = choice(all_samples)
    all_samples.remove(sample)
    return sample

for _ in range(10):
    print(rand_sample())

cbc
caa
acb
bbc
abc
cac
aaa
ccb
aac
acc

Demo

from itertools import product
from random import shuffle
list = product('abc', repeat=3))
shuffle(list)

Should do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM