Best way to randomly assign an attribute to 10% of objects in a list?

  1. How does that work? I read the documentation to say sample would be a new list. Does sample point to objects in the original list?

  2. For future viewers of this comment - I was using a pygame sprite group, so if you are, you will need to do (list(object_list)...) for this to work.

  3. So you want exactly 10% of elements to have the attribute? Shuffle the list, set the attribute on the first 10% of items, then shuffle again.

  4. If you wanted to implement a solution, you could always keep track of how many objects need to be assigned and how many are left. So at the start if there are 90 objects, you have 90 left and 9 need to be assigned. Go through the list from the start and at each element, assign it an attribute with (number that need to be assigned)/(number of objects left). When an object gets assigned, subtract one from the number of objects that need to be assigned. And subtract one from the number of objects left every time you consider an object.

  5. You could use, random.shuffle and assign the attribute to first 10% of elements, then shuffle again

  6. Maintain another list containing references to all objects with the attribute that you want. That way you instantly know how many objects have that that attribute and which ones they are.

Leave a Reply

Your email address will not be published. Required fields are marked *

Author: admin