为什么我的程序中的remove()函数没有按预期工作?

时间:2017-09-16 02:09:38

标签: python-3.x

我正在为我的工作在Python 3.6中创建一个联系人管理程序,我正在尝试添加一个允许用户在列表中删除他们选择的单个联系人的功能。

但是,当我运行程序时,它不会删除所需的列表项。相反,它会返回此错误:

Traceback (most recent call last):
    File "C:/Users/cmanagerMain.py", line 10, in <module>
        deleteContact()
    File "C:\Users\cmanagerFunctions.py", line 23, in deleteContact
        contactList.remove(item)
ValueError: list.remove(x): x not in list

我对Python仍然有点新意,因此我无法确定出错的地方。

我希望有人能够识别我的错误,以便我可以从中学习并提出解决方案。

以下是代码:

contactList = []


class Contact:
    name = ""
    number = ""


def addContact():
    print()
    contact = Contact()
    contact.name = input("Enter contact name: ")
    contact.number = input("Enter contact number: ")
    contactList.append(contact)
    print("Contact added.")
    print()

def deleteContact():
    print()
    item = Contact()
    item.name = input("Enter contact to be deleted: ")
    item.number = input("Enter the number of contact: ")
    contactList.remove(item)
    print()

def getMenuChoice():
    print("1. Add new contact")
    print("2. Print all contacts")
    print("3. Delete a contact")
    print("4. Quit")
    return input("Please enter your choice (1-4): ")


def printContacts():
    print()
    print("Printing contacts...")
    for itm in contactList:
        print(itm.name + "," + itm.number)
    print()


while True:
   choice = getMenuChoice()
   if choice == "1":
       addContact()
   elif choice == "2":
       printContacts()
   elif choice == "3":
       deleteContact()
   elif choice == "4":
       print("Goodbye")
   else:
       continue

1 个答案:

答案 0 :(得分:0)

要从项目编号(从零开始)传递的列表中删除元素,而不是项目本身。

相关问题