Home > database >  randomly replace item in list
randomly replace item in list

Time:01-11

I have two lists A =[2,3,4,5,33,42,21] and B = [1,11,35,48,19] I want to randomly delete two items of list B and replace with two random items from list A for 200 iteration. I used this code but only one item of B replace with A. how can I do that?

import random

A = [2,3,4,5,33,42,21]
B = [1,11,35,48,19]

x = random.randrange(0,5)
i = A[x]
A[x] = B[x]
B[x] = i
print(A)
print(B)

CodePudding user response:

Use random.sample.

import random

list_a = [2, 3, 4, 5, 33, 42, 21]
list_b = [1, 11, 35, 48, 19]

a_index1, a_index2 = random.sample(range(len(list_a)), k=2)
b_index1, b_index2 = random.sample(range(len(list_b)), k=2)
list_a[a_index1], list_b[b_index1] = list_b[b_index1], list_a[a_index1]
list_a[a_index2], list_b[b_index2] = list_b[b_index2], list_a[a_index2]

The only thing needed to be added here is to put it in a loop and loop 200 times.

random.sample chooses k unique choices from an iterable so there won't be a case where it chooses the same integer twice in an iteration.

If you attempt to use the same index for both list_a and list_b you will never replace the final 2 elements in list_a since list_b is shorter and does not have an equivalent index.

CodePudding user response:

You almost had it:

import random

A = [2,3,4,5,33,42,21]
B = [1,11,35,48,19]


for _ in range(400):
    x = random.randrange(0,5)
    A[x], B[x] = B[x], A[x]
print(A)
print(B)

You want to loop 400 times since you want to change 2 items for each iteration and you want to iterate for 200 times. You could also do this:

import random

A = [2,3,4,5,33,42,21]
B = [1,11,35,48,19]


for _ in range(200):
    x = random.randrange(0,5)
    y = random.randrange(0,5)
    while y == x:
        y = random.randrange(0,5)
    A[x], B[x] = B[x], A[x]
    A[y], B[y] = B[y], A[y]
print(A)
print(B)

This has the "benefit" that the 2 replacements are never the same(which you might have asked?)

  •  Tags:  
  • Related