Python接受用户输入并从lis中删除该输入

2024-10-16 20:47:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经试了几天了。我得在一个包含动物园动物的文件里读。(例如,['ID','Name','Species'])接下来,必须接受用户的ID选择并从列表中删除。这就是我目前为止所做的。我被卡住了,在这一部分完成之前不能继续。我很感谢你的评论。同样使用python3。在

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)

编辑:

例如,该文件包含以下项。 [['1','胡须','西伯利亚虎\n'],['2','Babbity','比利时野兔\n'],['3','Hank','spoted Python\n'],['17','Larry','Lion\n'],['10','Magilla','Eastern Gorilla\n'],['1494','Jim','Grizzy Bear\n']]

我想尝试删除,例如,ID 2,Babbity,比利时野兔

这是我不能用我当前的代码做的


Tags: 文件toinidinputlinepopfile1
2条回答

list.pop()删除列表的最后一个元素。你可能想要file.remove(c)。另外,删除file1 = list(c)。我不知道为什么会这样。在

list.pop接受index作为参数。对于列表,它只能是整数。另外,list('abc') != ["abc"],而是{},因为str的迭代协议(它按字母顺序排列)。在

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")

然后,要使用更改更新文件:

^{pr2}$

相关问题 更多 >