Reputation: 115
Ive two lists and Id like to have specific elements of sublist in A (the y's) to be randomly replaced with elements from list B.
A=[[x, y], [z, y], [b, y]]
B=[y1, y2]
So some possible output could look something like this,
A=[[x, y1], [z, y1], [b, y2]]
A=[[x, y2], [z, y2], [b, y2]]
A=[[x, y2], [z, y2], [b, y1]]
but there would be only 1 output at a time. And if the codes run again, there could be another output and so one. Im not really sure how to approach this so help is appreciated.
Upvotes: 0
Views: 57
Reputation: 1359
import random
A=[["x", "y"], ["z", "y"], ["b", "y"]]
B=["y1", "y2"]
for elem in A:
i = random.randint(0,1)
elem[1] = B[i]
print(A)
Upvotes: 0
Reputation: 117856
You could preserve the [0]
element, then use random.choice
to randomly select an element from B
to use as the [1]
element.
import random
def random_replace(A, B):
return [[i[0], random.choice(B)] for i in A]
Some examples
>>> random_replace(A, B)
[['x', 'y2'], ['z', 'y2'], ['b', 'y1']]
>>> random_replace(A, B)
[['x', 'y2'], ['z', 'y1'], ['b', 'y1']]
>>> random_replace(A, B)
[['x', 'y1'], ['z', 'y2'], ['b', 'y2']]
Upvotes: 5