[英]Python accepting user input and deleting that input from a list
I have been trying this for a few days now. 我已经尝试了几天了。 I have to read in a file containing zoo animals. 我必须阅读一个包含动物园动物的文件。 (ie ['ID', 'Name', 'Species']) Next, have to accept the user's ID choice and delete from the list. (即['ID','Name','Species'])接下来,必须接受用户的ID选择并从列表中删除。 This is what I so far. 这就是我到目前为止。 I am stuck and can't proceed further until this section is complete. 我被困住了,在本节完成之前无法继续进行。 I appreciate any comments. 我感谢任何评论。 Also using python 3. 也使用python 3。
f = open('ZooAnimals.txt', 'r') #read in file
file = [line.split(',') for line in f.readlines()] #turn file into list
c = input("What ID would you like to delete? ") #accept user input
file1 = list(c)#turn user input into a list item
list.pop(file1) #suppose to pop out the value
print(file)
EDIT: 编辑:
The file contains the following items for example. 该文件例如包含以下项目。 [['1', 'Whiskers', 'Siberian Tiger\\n'], ['2', 'Babbity', 'Belgian Hare\\n'], ['3', 'Hank', 'Spotted Python\\n'], ['17', 'Larry', 'Lion\\n'], ['10', 'Magilla', 'Eastern Gorilla\\n'], ['1494', 'Jim', 'Grizzy Bear\\n']] [['1','胡须','西伯利亚虎\\ n'],['2','巴比蒂','比利时野兔\\ n'],['3','汉克','斑点蟒蛇\\ n' ],['17','Larry','Lion \\ n'],['10','Magilla','Eastern Gorilla \\ n'],['1494','Jim','Grizzy Bear \\ n' ]]
I want to try and delete for example, ID 2, Babbity, Belgian Hare 我想尝试删除例如ID 2,Babbity,比利时野兔
This is what I can't do with my current code 这是我无法使用当前代码执行的操作
list.pop
accepts an index
as an argument. list.pop
接受index
作为参数。 For lists, this can only be an integer. 对于列表,只能是整数。 Also, list('abc') != ["abc"]
, but rather ["a", "b", "c"]
because of str
's iteration protocol (it goes by letter). 同样, list('abc') != ["abc"]
,而是["a", "b", "c"]
str
]的迭代协议(按字母list('abc') != ["abc"]
,而不是["a", "b", "c"]
。
with open("ZooAnimals.txt") as zoo_animals_txt:
# [("123", "cat", "felis catus"), ...]
animals = [line.split(",") for line in zoo_animals_txt]
user_input = input("What ID would you like to delete? ")
for index, (id_, name, species) in enumerate(animals):
if id_ == user_input:
animals.pop(index)
break
print("The remaining animals are:")
print(*animals, sep="\n")
Then, to update the file with the change: 然后,使用更改来更新文件:
with open("ZooAnimals.txt", "w") as zoo_animals_txt:
for animal_stats in animals:
print(",".join(animal_stats), file=zoo_animals_txt)
list.pop()
removes the last element of a list. list.pop()
删除列表的最后一个元素。 You probably want file.remove(c)
. 您可能需要file.remove(c)
。 Also, remove file1 = list(c)
. 同样,删除file1 = list(c)
。 I'm not sure why that's there. 我不确定为什么会在那里。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.