2017-09-16 51 views
0

我正在为我的工作在Python 3.6中创建一个联系人管理程序,我正在尝试添加一个函数,允许用户在列表中删除他们选择的单个联系人。为什么我的程序中的remove()函数无法按预期工作?

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

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 

回答

0

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

相关问题