[英]How do I remove a variable out of a list?
I have compiled a list at the very beginning consisting of the integers 0, 1 and 2. If user's choice of a number is not the same choice as the PC's, I want the PC's and user's number to be removed from the original list. 我在最开始编译了一个由整数0,1和2组成的列表。如果用户选择的数字与PC的选择不同,我希望将PC和用户的号码从原始列表中删除。 Unfortunately I have not been able to do so, as Python returns me a wrong list. 不幸的是我无法这样做,因为Python给我一个错误的列表。 Even if the computer chose "1", it will not be removed from the list. 即使计算机选择“1”,它也不会从列表中删除。
How can I return a modified list with only the number not chosen by the user or the computer? 如何仅使用用户或计算机未选择的编号返回修改后的列表?
import random
while True:
list_of_numbers = [0,1,2]
chosen_number_user = input("Please choose a number between 0-2")
int(chosen_number_user)
chosen_number_PC = random.choice(list_of_numbers)
if int(chosen_number_user) == int(chosen_number_PC):
print ("You have chosen the correct number!")
break
elif chosen_number_user != chosen_number_PC:
for chosen_number_PC in list_of_numbers:
list_of_numbers.remove(chosen_number_PC)
print(list_of_numbers)
for chosen_number_user in list_of_numbers:
list_of_numbers.remove(chosen_number_user)
print(list_of_numbers)
break
else:
print ("Something has gone wrong")
Say I chose the number 2 and the computer chose number 1. I then expected the list_of_numbers to contain only the 0. However, the list is completely empty. 假设我选择了数字2,计算机选择了数字1.然后我预计list_of_numbers只包含0.但是,列表完全为空。
You forgot to convert chosen_number_PC to int: 您忘了将selected_number_PC转换为int:
list_of_numbers.remove(int(chosen_number_PC))
You can also use: 您还可以使用:
del list_of_numbers[int(chosen_number_PC)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.