[英]How to remove things from file with user input
I have created a file with content.我创建了一个包含内容的文件。 The problem is that I know how to add things with
append
but I don't know how to remove things from the file with a user input.问题是我知道如何使用
append
添加内容,但我不知道如何使用用户输入从文件中删除内容。
The code is, the results
variable is dictionary:代码是,
results
变量是字典:
while True:
remover = int(input("What results do you want to remove "))
for line in enumerate(results, start = 1):
line.remove(remover)
print("{}".format(remover) + " is removed")
Would appreciate some help希望得到一些帮助
This seems like something that lends itself pretty well for a list comprehension.这似乎非常适合列表理解。
Assuming that results is a list of all the current results Please see the example below:假设结果是所有当前结果的列表请看下面的例子:
while True:
remover = input("What results do you want to remove ")
results = [line for line in results if line != remover]
print("{}".format(remover) + " is removed")
print("List currently has the following elements {}".format(results)
In the example below, for every iteration of the loop:在下面的示例中,对于循环的每次迭代:
For more information on how list comprehensions work, please see: https://www.pythonforbeginners.com/basics/list-comprehensions-in-python有关列表推导如何工作的更多信息,请参阅: https : //www.pythonforbeginners.com/basics/list-comprehensions-in-python
If however you just want to get your example to work, you can refactor it into this:但是,如果您只想让您的示例工作,您可以将其重构为:
while True:
remover = int(input("What results do you want to remove "))
for line in results:
if line == remover:
results.remove(remover)
print("{}".format(remover) + " is removed")
What I changed here:我在这里改变了什么:
Please note that if you're not working with a list of integers, but strings you need to remove the typecasting to an int请注意,如果您不使用整数列表,而是使用字符串,则需要将类型转换删除为 int
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.