Home > Enterprise >  Distribution of 2 lists randomly to another 2 lists
Distribution of 2 lists randomly to another 2 lists

Time:06-14

I have two lists A and B ,

and P1,P2

and I need to take A,B and randomly distribute them to lists P1,P2

A = [ A1,A2,A3,A4 = "A1","A2","A3","A4" ]

B = [n101,n102,n103,n104 = "101","102","103","104"]

This loop should distribute the lists 4 times randomly until all P1 and P2 get filled up randomly

for i in range(4):
    if(i <= 3) and a == 3:
        P1 = range(A1,A2,A3,A4,n101,n102,n103,n104)
        a  = 1
    
    if(i <= 3) and b == 3:
        P2 = range(A1,A2,A3,A4,n101,n102,n103,n104) 
        b  = 1
    

expected result

P1 = A4,101,104,A2
P2 = 102,A3,103,A1

P1,P2 random distribution from A,B

CodePudding user response:

Use sample method in the random module for this. Since you don't want duplication in the second list, you can use a for loop to exclude all the values available in both P1 and A B and create a new list. Then you can use sample to again get a list with random values.

import random

A = ["A1","A2","A3","A4"]
B = ["101","102","103","104"]

P1 = random.sample(A   B, 4)

new_list = []

for x in A B:
    if x not in P1:
        new_list.append(x)
        
P2 = random.sample(new_list, 4)

print(P1)
print(P2)

Output:

['104', '102', 'A4', '103']
['101', 'A2', 'A1', 'A3']

Use len(A) as the 2nd argument in sample() method, if the length of your list is not always 4.

  • Related