Thaeer M Sahib
Thaeer M Sahib

Reputation: 35

How can two items be randomly selected and moved from one list to another list?

I want a method to select two elements (as sub-lists) from one list and then move them to another list, while removing them from the first list.

My code:

A=[[17, 4, 10, 18, 11], [23, 16, 24, 29, 19, 12, 22], [15, 2, 32, 30, 20, 7, 25], [33, 21, 5, 13, 6, 28, 26, 31], [27, 8, 9, 14, 3]]
B = random.sample(A, 2)
      print("B",B)

My results:

B [[27, 8, 9, 14, 3], [33, 21, 5, 13, 6, 28, 26, 31]]

Expected results:

A [[17, 4, 10, 18, 11], [23, 16, 24, 29, 19, 12, 22], [15, 2, 32, 30, 20, 7, 25]]
B [[27, 8, 9, 14, 3], [33, 21, 5, 13, 6, 28, 26, 31]]

Upvotes: 1

Views: 585

Answers (4)

Cory Kramer
Cory Kramer

Reputation: 117866

You could randomly select an index from A and pop/append from one list to the other

import random

A = [[17, 4, 10, 18, 11], [23, 16, 24, 29, 19, 12, 22], [15, 2, 32, 30, 20, 7, 25], [33, 21, 5, 13, 6, 28, 26, 31], [27, 8, 9, 14, 3]]
B = []

for _ in range(2):
    B.append(A.pop(random.randrange(0, len(A))))

Result

>>> A
[[15, 2, 32, 30, 20, 7, 25], [33, 21, 5, 13, 6, 28, 26, 31], [27, 8, 9, 14, 3]]
>>> B
[[23, 16, 24, 29, 19, 12, 22], [17, 4, 10, 18, 11]]

Note that you need to re-evaluate len(A) within your loop when you call randrange since the size is decreasing as you pop elements.

Upvotes: 4

nocibambi
nocibambi

Reputation: 2421

A not too performant solution:

import random

A = [
    [17, 4, 10, 18, 11],
    [23, 16, 24, 29, 19, 12, 22],
    [15, 2, 32, 30, 20, 7, 25],
    [33, 21, 5, 13, 6, 28, 26, 31],
    [27, 8, 9, 14, 3],
]

B = []
for i in random.sample(range(len(A)), 2):
    B.append(A[i])
    A.remove(A[i])

A, B
>>>
([[17, 4, 10, 18, 11],
  [23, 16, 24, 29, 19, 12, 22],
  [33, 21, 5, 13, 6, 28, 26, 31]],
 [[15, 2, 32, 30, 20, 7, 25], [27, 8, 9, 14, 3]])

A more effective one:

idx = sorted(random.sample(range(len(A)), 2))
A_new = []
B = []
for i, a in enumerate(A):
    if i in idx:
        B.append(a)
        idx = idx[1:]
    else:
        A.append(a)

A = A_new

Upvotes: 2

Thulfiqar
Thulfiqar

Reputation: 392

one possible solution

import random 
A=[[17, 4, 10, 18, 11], [23, 16, 24, 29, 19, 12, 22], [15, 2, 32, 30, 20, 7, 25], [33, 21, 5, 13, 6, 28, 26, 31], [27, 8, 9, 14, 3]]
B_with_index = random.sample((list(enumerate(A))), 2)

B = []
for element in B_with_index:
    
    B.append(element[1])
    A.pop(element[0])
    

Upvotes: 1

Bernat Felip
Bernat Felip

Reputation: 363

A very simple way would be to just iterate over the elements you have in B and removing them from A after the sampling.

for el in B:
    A.remove(el)
>>> A
[[15, 2, 32, 30, 20, 7, 25], [33, 21, 5, 13, 6, 28, 26, 31], [27, 8, 9, 14, 3]]
>>> B
[[23, 16, 24, 29, 19, 12, 22], [17, 4, 10, 18, 11]]

Upvotes: 1

Related Questions