by replacing certain elements in a list with elements from another list python – java

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']]

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top