【问题标题】:user choicen variable removed off list用户选择的变量已从列表中删除
【发布时间】:2019-09-02 20:52:39
【问题描述】:
我有一个数组,我想删除或添加用户选择的项目,例如my_list.remove(input("which item do you remove")。我该如何正确地做到这一点?
我希望我编写的代码可以像普通删除命令一样从列表中删除用户选择的项目(如果它在列表中),除了用户输入
我是否遗漏了一些明显的东西?几天前我开始使用python,但我不太擅长。谢谢。
【问题讨论】:
标签:
python
arrays
python-3.x
python-2.7
【解决方案1】:
这是实现此目的的 python(2 或 3)脚本:
from __future__ import print_function
from builtins import input
mylist = ['apple', 'banana', 'pineapple']
mylist.pop(mylist.index(input('Which element do you want to remove from the list?')))
print(mylist)
用法:
$python foo.py
Which element do you want to remove from the list?apple
['banana', 'pineapple']
$ python3 foo.py
Which element do you want to remove from the list?pineapple
['apple', 'banana']
如果您尝试删除列表中没有的内容,错误实际上很明显:
Which element do you want to remove from the list?peach
Traceback (most recent call last):
File "foo.py", line 4, in <module>
mylist.pop(mylist.index(input('Which element do you want to remove from the list?')))
ValueError: 'peach' is not in list
【解决方案2】:
例如,您有列表 ['a', 'e', 'i', 'o', 'u'] 并且您想删除此列表之间的任何值
li = ['a', 'e', 'i', 'o', 'u']
remove_value = input("Which item do you want to remove: ")
li.remove(remove_value)
print(li)
输出将是:
>>> Which item do you want to remove: i # this is the value you want to remove
>>> ['a', 'e', 'o', 'u']
更多详情:More on Lists
【解决方案3】:
我在下面写了一个简单的python演示。您可以根据需要删除或添加项目。
# -*- coding: UTF-8 -*-
hobbies_list = ['cooking', 'basketball', 'walking', 'reading']
def remove_hobby():
target = input("Which item do you want to remove: ").lower()
if target in hobbies_list:
hobbies_list.remove(target)
else:
print("This item {} does not exist".format(target))
def add_hobby():
target = input("Which item do you want to add: ").lower()
if target in hobbies_list:
print("This item {} does not exist".format(target))
else:
hobbies_list.append(target)
print("This item {} add success ".format(target))
if __name__ == '__main__':
print("current hobbies:{}".format(','.join(hobbies_list)))
remove_hobby()
print("current hobbies:{}".format(','.join(hobbies_list)))
add_hobby()
print("current hobbies:{}".format(','.join(hobbies_list)))