简体   繁体   English

用另一个列表中的元素随机替换列表中的某些元素,python

[英]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 中子列表的特定元素(y 的)被列表 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.但一次只有 1 个输出。 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.您可以保留[0]元素,然后使用random.choiceB随机选择一个元素用作[1]元素。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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