random - Permutations of several lists in python efficiently -


i'm trying write python script generate random permutations of several lists without repeating

i.e. [a,b] [c,d] a, c b,c, a,d b,d 

i can generate every permutation using following, result non random:

for r in itertools.product(list1, list2):         target.write("%s,%s" % (r[0], r[1]) 

does know way can implement such can extract 2 permutations, , random ensure never repeated?

you can use random.choice():

>>> itertools import product >>> import random >>> l1 = ['a', 'b', 'c'] >>> l2 = ['d', 'e', 'f'] >>> prod = tuple(product(l1, l2)) >>>  >>> random.choice(prod) ('c', 'e') >>> random.choice(prod) ('a', 'f') >>> random.choice(prod) ('c', 'd') 

or use nested list comprehension creating products:

>>> lst = [(i, j) j in l2 in l1] 

if don't want produce duplicate items can use set object create set object product without specified order can pot items it:

>>> prod = set(product(l1, l2)) >>>  >>> prod.pop() ('c', 'f') >>> prod.pop() ('a', 'f') >>> prod.pop() ('a', 'd') 

or use shuffle in order shuffle iterable, @ayhan has suggested in answer.


Comments

Popular posts from this blog

javascript - How to get current YouTube IDs via iMacros? -

c# - Maintaining a program folder in program files out of date? -

emulation - Android map show my location didn't work -