vendredi 24 juin 2022

Random selection not already in a list Python [closed]

I am trying to make random selection from all_items list for each type of item in types.

This needs to happen in such a way that total number of items in each list that gets added to selection for each type should be the as per the he value of type.

All items in selection should all be unique no matter which list they belong to.

My code below:

all_items = ['G1Item1', 'G1Item2', 'G1Item3', 'G1Item4',  'G1Item5', 'G1Item6', 'G2Item1', 'G2Item2', 'G2Item3', 'G2Item4', 'G2Item5', 'G2Item6',]
types = {'A': 1, 'B': 3, 'C': 5, 'D': 2}

check = list()
# selection = dict()

for i in types:
    
    while any(item in pick for item in selection) == True:
    
        pick = random.sample(all_items, types[i])
    
    check.extend(pick)
#     selection.update({i: pick})

But when I access the value of selection, I get:

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Input In [13], in <cell line: 4>()
      6 while any(item in pick for item in selection) == True:
      8     pick = random.sample(all_items, types[i])
---> 10 check.extend(pick)

NameError: name 'pick' is not defined

I am not sure how to ensure that any of my random selection is not already park of check.

Hope this makes sense.

Any help would be appreciated.




Aucun commentaire:

Enregistrer un commentaire