I have two lists
a_list = ['a', 'b', 'c']
b_list = ['1', '2', '3']
What is the best way to randomly delegate list values from b_list to great tuples in a new list:
c_list = [('a','1'), ('b','3'), ('c','1')]
I have two lists
a_list = ['a', 'b', 'c']
b_list = ['1', '2', '3']
What is the best way to randomly delegate list values from b_list to great tuples in a new list:
c_list = [('a','1'), ('b','3'), ('c','1')]
import random
a_list = ['a', 'b', 'c']
b_list = ['1', '2', '3']
print [(a,random.choice(b_list)) for a in a_list]
Output:
[('a', '3'), ('b', '1'), ('c', '3')]
Shuffling the lists and zip
them would get your job done.
import random
a_list = ['a', 'b', 'c']
b_list = ['1', '2', '3']
random.shuffle(a_list)
random.shuffle(b_list)
c_list = zip(a_list, b_list)
Or if you don't want the one to one mapping then you may also use :
import random
a_list = ['a', 'b', 'c']
b_list = ['1', '2', '3']
c_list = [(i, random.choice(b_list)) for i in a_list]
As in your output I could see repeated values. Use below.
Without repetition:
random.shuffle(b_list)
print zip(a_list, b_list)
With repetition:
print [ (i,random.choice(b_list)) for i in a_list ]
import random
from functools import partial
a_list = ['a', 'b', 'c']
b_list = ['1', '2', '3']
r= partial(random.choice,b_list)
list(zip(a_list,[r(),r(),r()]))
[('a', '1'), ('b', '2'), ('c', '2')]