I'm trying to make a function that takes a random variable from a sublist and removes it after it is selected. But for some reason, when I use a variable to define what to be removed, it removes from multiple sublists, while actually not removing anything from those sublists at all? I can't describe this very well because I don't understand it well myself. Here's some code that I wrote to try and duplicate the problem:
import random
greet = [[1,"Hello!"],[2,"Hi!"], [3,"Howdy!"]] person = [["John", greet], ["Sally", greet], ["Frank", greet]]
while True:
#This is meant to catch the error random gives when there is an empty list, so it continues if there's an empty list.
#When all lists in person[0][1] and [1][1] and so on and so forth are empty, there is a break function below.
try:
person_select = random.choice(person)
greet_select = random.choice(person_select[1])
person_and_greet_order = [person_select[0], greet_select[1], greet_select[0]]
print(person_and_greet_order)
#This should be activating, but it isn't, leading to an infinite loop
if person[0][1]==[] and person[1][1]==[] and person[2][1]==[]:
print("Everyone greeted!")
break
#Tests to see if greeting was used on person, then remove that greeting from the list so it can't be used again.
elif person_and_greet_order[0]=="John":
person[0][1].remove(greet_select)
print(person)
elif person_and_greet_order[0]=="Sally":
person[1][1].remove(greet_select)
print(person)
elif person_and_greet_order[0]=="Frank":
person[2][1].remove(greet_select)
print(person)
#The else is here to see if it's properly detecting the names.
else:
break
except:
continue
Here's what you'll get from it:
['Frank', 'Hello!', 1] [['John', [[2, 'Hi!'], [3, 'Howdy!']]], ['Sally', [[2, 'Hi!'], [3, 'Howdy!']]], ['Frank', [[2, 'Hi!'], [3, 'Howdy!']]]] ['John', 'Hi!', 2] [['John', [[3, 'Howdy!']]], ['Sally', [[3, 'Howdy!']]], ['Frank', [[3, 'Howdy!']]]] ['Frank', 'Howdy!', 3] [['John', []], ['Sally', []], ['Frank', []]]
(And after this it loops to infinity because the if statement doesn't see that the lists are empty, even though they are?)
As you can see, it removes the value from EVERY sublist instead of the specific sublist, when I need it to just remove a value from one. And the empty lists are not registering as empty lists even though they are empty. I'm really new to python and I don't know anything I can do here. I'm at the end of my rope. Any suggestions?
Aucun commentaire:
Enregistrer un commentaire