Reputation: 39
I have two lists a
& b
and I need to pick a random element of a[i]
and b[i]
and generate z
.
a = [1, 0, 1, 1, 0, 1]
b = [1, 1, 0, 1, 0, 0]
z = [1, 0, 1, 1, 0, 0]
I used the below mentioned code:
import random
z = []
for i in range(6):
value = random(a[i],b[i])
z.append(value)
print z
and I get the following error:
TypeError: 'module' object is not callable
Upvotes: 0
Views: 38
Reputation: 5797
First off all you have to import random module.
import random
Then you can call any of its method:
random.random()
Furthermore you have should choose random.choice()
:
value = random.sample([a[i],b[i]], 1)
Upvotes: 0
Reputation: 39052
You can use random.choice
(docs here).
Return a random element from the non-empty sequence seq.
It selects one value from a list of values. For each iteration, you can just create a list of a[i]
and b[i]
.
for i in range(6):
value = random.choice([a[i],b[i]])
z.append(value)
print( z)
# [1, 1, 1, 1, 0, 0]
Another option is to use random.sample
where k=1
here and [a[i],b[i]]
is the population as following
Return a k length list of unique elements chosen from the population sequence or set
value = random.sample([a[i],b[i]], 1)
z.append(value[0])
Here value[0]
is used because value
is a list containing single element so by using [0]
you get that element without the list.
Upvotes: 1
Reputation: 2843
You're calling random
as if it's a function, when in fact it's a module. You need to use random.choice
to choose one of the two options:
value = random.choice([a[i],b[i]])
Upvotes: 0