Reputation: 369
I am a bit new to python so I am wondering if there is a more efficient way of accomplishing something. Basically I need to create an array of values which come from one of two other arrays depending on a random number (0 or 1) Currently its pretty easy to implement using a for loop, however I am just curious if there is a more elegant/python-ish way to accomplish this, it seems too clunky for how python is designed:
import random
xySet = ['x', 'y']
xP = [10.1, 11.2, 12.3]
yP = [12.5, 13.2, 14.1]
nObser = 10
x = []
p = []
randVals = [random.randint(0,1) for i in range(nObser)]
print randVals
for i in range(nObser):
x.append(xySet[randVals[i]])
if randVals[i]:
p.append(xP[random.randint(0,2)])
else:
p.append(yP[random.randint(0,2)])
print x
print p
This gives me the correct output I would expect:
[1, 1, 1, 0, 1, 1, 1, 0, 1, 0]
['y', 'y', 'y', 'x', 'y', 'y', 'y', 'x', 'y', 'x']
[12.3, 11.2, 10.1, 13.2, 10.1, 11.2, 12.3, 14.1, 10.1, 13.2]
Thanks!
Upvotes: 0
Views: 59
Reputation: 117856
You could use a pair of list comprehensions
>>> from random import choice
>>> x = [choice(xySet) for _ in range(nObser)]
>>> p = [choice(xP) if v == 'x' else choice(yP) for v in x]
>>> x
['y', 'y', 'y', 'x', 'x', 'x', 'y', 'x', 'x', 'x']
>>> p
[14.1, 13.2, 14.1, 10.1, 10.1, 12.3, 13.2, 12.3, 11.2, 10.1]
In the first list comprehension, you use random.choice
to randomly pick 'x'
or 'y'
.
Then in the second list comprehension, you iterate over your x
list and sample (again using random.choice
) from the appropriate list.
Upvotes: 3