搜索列表中包含列表并删除我们搜索的特定列表

时间:2015-10-28 00:32:35

标签: python list python-2.7

我有一个列表,其中包含列表:

Contact_list = [["Smith", "John", "780 555 3234", "jsmith@gsacrd.ab.ca"], ["Pitts", "Harry", "780 555 7329", "hpitts@gmail.com"], ["Fields", "Sara", "780 555 8129", "sfields@hotmail.com"], ["Smith", "Jane", "780 555 2819", "jsmith@gmail.com"], ["Unger", "Felix", "302 555 3819", "funger@universal.org"]]

我想搜索名字或姓氏并编辑该特定联系人'具体要素。我写了这样的代码:

def EditContact():
    editby = raw_input('| 1 | To Search contact and Edit by FirstName:\n| 2 | To Search contact and Edit by LastName: ')
    if editby == '1':
        FirstName = raw_input('Firstname: ')
        EditByFirstName(FirstName)
    elif editby == '2':
        LastName = raw_input('Lastname: ')
        EditByLastName(LastName)
    else:
        print("\n----------------------\nIncorrect choice.\n----------------------\n")

你可以理解尝试在这里找到名字或姓氏的联系方式并将它们发送到这里的def

def EditByFirstName(First):
    for x in Contact_list:
        if (x[1] == First)  :
            print '\n----------------------\n',x[1],x[0],'Named Contact Found!!!! \n----------------------\n'
            ChangeInformation(x)
        else:
            print "\nThis Contact Does Not Exist!!\n----------------------\n"
def EditByLastName(Last):
    for x in Contact_list:
        if (x[1] == Last)  :
            print '\n----------------------\n',x[1],x[0],'Named Contact Found!!!! \n----------------------\n'
            ChangeInformation(x)
        else:
            print "\nThis Contact Does Not Exist!!\n----------------------\n"

直到这里一切都好。但是在这里参加List中的新事物会给出错误。问题在于这段代码,但无法找出导致它的原因:

def ChangeInformation(x):
    print "| 1 | To Edit Firstname"
    print "| 2 | To Edit Lastname"
    print "| 3 | To Edit PhoneNumber"
    print '| 4 | To Edit Email'
    Edit_Choice = raw_input("Please make a choice:")
    if Edit_Choice == '1':
        NewFirstName = input("Please Enter New Firstname: ")
        Contact_list[x[1]] = (NewFirstName)
        return Contact_list
    elif Edit_Choice == '2':
        NewLastName = raw_input("Please Enter New Lasttname: ")
        Contact_list[x[0]] = NewLastName
        return Contact_list
    elif Edit_Choice == '3':
        NewNumber = raw_input("Please Enter New Number: ")
        Contact_list[x[2]] = NewNumber
        return Contact_list
    elif Edit_Choice == '4':
        NewEmail = raw_input("Please Enter New Email: ")
        Contact_list[[x[3]]]= NewEmail
        return Contact_list
    else:
        print("\n----------------------\nIncorrect choice.\n----------------------\n")

1 个答案:

答案 0 :(得分:1)

当您致电ChangeInformation(x)时,您正在通过x成员Contact_list,这是一个列表本身。现在,在ChangeInformation中,您可以执行以下操作

Contact_list[x[0]] = NewLastName

这会产生类型错误,因为x[0]可能会导致int以外的类型的对象对列表索引无效。你应该改变它

x[0] = NewLastName

因为您已经传递了列表成员并删除了return语句。