Python 每当用户输入特定内容时,从列表中删除值
假设我有一个列表(这是一个例子,但概念是一样的):Python 每当用户输入特定内容时,从列表中删除值,python,list,input,Python,List,Input,假设我有一个列表(这是一个例子,但概念是一样的): List=[“我”、“恨”、“不”、“爱”、“你”。] 如何从列表中删除多个项目?我基本上希望该计划: 从用户处获取输入。 怎么用?每当用户键入delete x y x和y表示列表中项目的编号 每当人员键入“Delete”时,从列表中删除指定的项目(将其视为一个命令。同样,从第1点删除也是如此) 例如: 一旦用户输入并按下enter键,程序将从列表中删除第二个和第三个值(在本例中,从我们人类的角度来看,“仇恨”和“不要”,因为它们分别占据第二
List=[“我”、“恨”、“不”、“爱”、“你”。]
如何从列表中删除多个项目?我基本上希望该计划:
怎么用?每当用户键入
delete x y
x和y表示列表中项目的编号
例如:
问题是我不知道怎么做。有人能帮我吗?我希望我说得够清楚了。如果没有,我可以尝试用另一种方式解释。您可以尝试以下方法:
List = ["I", "hate", "don't", "love", "you."]
command, *vals = input("Enter command: ").split()
if command=='delete':
print([elem for i, elem in enumerate(List, start=1) if i not in list(map(int, vals))])
输出:
Enter command: delete 2 3
['I', 'love', 'you.']
注意:如果输入的数字大于列表长度,则不会产生任何作用。我希望这能有所帮助。我第一次在这里回答问题,所以让我知道这是否可以,如果你需要更多的帮助
lst = ["I", "hate", "don't", "love", "you."]
从用户那里获取输入。这将以字符串的形式保存。
我们将以用户输入delete23为例
command = input("Enter a command")
根据步骤2,此变量将用于保存命令
saved_command = None
如果其命令的第一个字是“delete”,则执行第一个if块
如果保存的命令仍然为“无”
if command.startswith("delete") and not saved_command:
# This makes the saved_command a list. It splits the
# command string where there are spaces so it becomes
# ["delete", "2", "3"]. Then, we remove 'delete' so
# it is just the numbers
saved_command = command.split().remove("delete")
如果用户给出的命令以
“删除并保存”命令不是“无”。如果第一个
如果在该if块中设置了保存的_命令,则执行if块
if command.startswith("delete") and saved_command:
# Loops through the numbers given. Note that with this, if the user
# passes in something which is not a number, the program will crash
for number in saved_command:
# Removes each item from the original list.
# Note that normally, items are indexed from 0 onwards
# so to have it be in the way you wanted, i.e. 1 is the first
# item, I've subtracted 1 from the number.
# int() is used because the numbers were given as user input so
# they would still be strings
try:
lst.pop(int(number) - 1)
except KeyError:
pass
请注意,要继续保存保存的_命令值,程序必须在循环内运行,尽管您可能知道这一点。如果该数字大于列表的长度,该怎么办?你试过什么?这只是一个简单的程序你的意思是你的程序通过
input()
接受“delete…”
指令?这是一个很好的问题,deadshot。我最终会自己考虑的。我会尽量不要要求太多的帮助^^;嗯,我试过一些东西,但它甚至不是我想要的。我编码说,如果用户键入“delete”(仅此而已),它将打印“您想删除列表中的哪些项目?”。我将输入设置为一个整数,并将其分配为一个变量(数字),然后,我将编码“List.pop(数字)”,然后它将从列表中删除该值。但是如果我输入2个数字就会出错。嗯,是的,提比。M.用户输入“delete x y”(x和y是数字),它应该删除与数字对应的值(例如,如果我输入1,那么它将删除第一个值,依此类推)
if command.startswith("delete") and saved_command:
# Loops through the numbers given. Note that with this, if the user
# passes in something which is not a number, the program will crash
for number in saved_command:
# Removes each item from the original list.
# Note that normally, items are indexed from 0 onwards
# so to have it be in the way you wanted, i.e. 1 is the first
# item, I've subtracted 1 from the number.
# int() is used because the numbers were given as user input so
# they would still be strings
try:
lst.pop(int(number) - 1)
except KeyError:
pass