How to use random.choice() in a list without a specific element?
Question:
Im currently writing a very simplified version of the board game Clue. I have a question on how to present new clues to the user.
The code has a list called clew_list which has all of the characters and guns available. The new clue is chosen randomly using random.choice(clue_list). My doubt is how to implement that function without taking into consideration the actual crime, which is also an element of clue_list.
The Crime is also chosen randomly using classes and the same method mentioned earlier.
Thank you
Answers:
You can create a new list and pick randomly in the new list
random.choice([element for clew_list in agents if !(isinstance(element, crime))])
You can have a while loop until you get what you were looking for. Might seem like a more rudimentary solution compared to the solution made by RCvaram, but if you agents list is big then the probability of picking the wrong thing goes down, and also creating a new list is pretty slow.
choice = random.choice(agents)
while !(isinstance(choice, crime):
choice = random.choice(agents)
Im currently writing a very simplified version of the board game Clue. I have a question on how to present new clues to the user.
The code has a list called clew_list which has all of the characters and guns available. The new clue is chosen randomly using random.choice(clue_list). My doubt is how to implement that function without taking into consideration the actual crime, which is also an element of clue_list.
The Crime is also chosen randomly using classes and the same method mentioned earlier.
Thank you
You can create a new list and pick randomly in the new list
random.choice([element for clew_list in agents if !(isinstance(element, crime))])
You can have a while loop until you get what you were looking for. Might seem like a more rudimentary solution compared to the solution made by RCvaram, but if you agents list is big then the probability of picking the wrong thing goes down, and also creating a new list is pretty slow.
choice = random.choice(agents)
while !(isinstance(choice, crime):
choice = random.choice(agents)