3

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')]
user47467
  • 1,045
  • 2
  • 17
  • 34
  • I think that question will help you: http://stackoverflow.com/questions/306400/how-do-i-randomly-select-an-item-from-a-list-using-python – Thargor Oct 15 '15 at 13:07
  • You don't use `2` from b_list, is that expected or do you want to use all values? – Andy Oct 15 '15 at 13:09
  • Sounds like a home work, did you have tried anything so far to figure it out? – Mazdak Oct 15 '15 at 13:09
  • 1
    @Andy this is expected, as I want it to randomly delegate values from b_list to a_list. c_list could well be a1,b1,c1 or a2, b2,c3 etc. – user47467 Oct 15 '15 at 13:13

4 Answers4

5
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')]
The6thSense
  • 8,103
  • 8
  • 31
  • 65
4

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]
ZdaR
  • 22,343
  • 7
  • 66
  • 87
1

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 ]
garg10may
  • 5,794
  • 11
  • 50
  • 91
1
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')]
LetzerWille
  • 5,355
  • 4
  • 23
  • 26