简体   繁体   中英

randomly replacing certain elements in a list with elements from another list, python

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM