【发布时间】:2020-09-28 21:34:18
【问题描述】:
我有一个保存为类属性的列表,我正在尝试删除该列表中的特定字典。
该项目是一个简单的项目,用户应该能够将项目添加到集合(保存在列表中)、编辑它们、按类型过滤搜索结果(之前添加到列表中)以及从列表中删除字典条目.
这里是构造函数:
class Item:
py_collection_list = []
def __init__(self, item_name: str, item_type: str, date_add, dom, item_info: str):
self.__id = Item.get_next_id()
self.item_name: str = item_name
self.item_type: str = item_type
self.date_add = date_add
self.dom = dom
self.item_info: str = item_info
Item.py_collection_list.append(self)
(Item 是超类,py_collection_list 是列表)
我能够使用以下代码创建过滤器:
def show_items():
print('View items by type \nComputer | Camera | Phone | Video Player ')
type_selection = input('Type> ')
print("{0:3}\t{1:20}\t{2:10}\t{3:10}".format("ID", "Item", "Date added", "Date manufactured"))
for i in Item.py_collection_list:
if type_selection == i.item_type:
print("{0:03d}\t{1:20}\t{2:10}\t{3:10}".format(i.get_id(), i.item_name, i.date_add, i.dom))
我使用了几个删除选项,这是最新的一个,但不起作用:
def delete_item():
print("{0:3}\t{1:20}\t{2:10}\t{3:10}".format("ID", "Item", "Date added", "Date manufactured"))
for i in Item.py_collection_list:
print("{0:03d}\t{1:20}\t{2:10}\t{3:10}".format(i.get_id(), i.item_name, i.date_add, i.dom))
remove_item = input("Type name of the item you would like to delete from collection> ")
if remove_item == i.item_name:
del [remove_item]
【问题讨论】:
-
Item.py_collection_list.remove(name)或Item.py_collection_list.pop(idx) -
感谢您的推荐。不幸的是,我收到了 2 个错误: ValueError: list.remove(x): x not in list and Item.py_collection_list.pop(remove_item) TypeError: 'str' object cannot be mapped as an integer
-
不相关,但您没有将字典附加到您的
list。您正在附加Item的实例。 -
您可以按值删除,也可以按索引弹出。在您的情况下,您需要
remove(i)
标签: python python-3.x list dictionary class-attributes