Python删除列表中的元组记录

时间:2015-12-04 18:21:48

标签: python

我正试图从我的列表中删除一个元组,我已经尝试过人们所说的一切,但仍然没有运气。我尝试了两种方法,一次删除记录,即使它不是我要删除的名称,第二种方法根本不删除。

record=[]
newrecord=[]
full_time=""
choice = ""
while (choice != "x"):
    print()
    print("a. Add a new employee")
    print("b. Display all employees")
    print("c. Search for an employee record")
    print("d. Delete an employee record")


    elif choice == "d":
        delete = str(input("Enter the name of the employee you would like to remove from the record: "))
        for d in record:
            if d == delete:
                record.remove(delete)

这不会删除任何内容。

如果我将其更改为:

elif choice == "d":
        delete = str(input("Enter the name of the employee you would like to remove from the record: "))
        record = [n for n in record if delete in record]

如果我这样做,它会删除所有。

这是我如何添加到列表

choice = input("Choose an option (a to f) or x to Exit: ")

if choice == "a":
    full_name = str(input("Enter your name: ")).title()
    job_title = str(input("Enter your job title: ")).title()

while full_time.capitalize() != "Y" or full_time.capitalize() != "N":
    full_time=input("Do you work full time (Y/N): ").upper()


    if full_time.capitalize() == "Y":
        break
    elif full_time.capitalize() == "N":
        break
        break

hourly_rate = float(input("Enter your hourly rate: £"))

number_years = int(input("Enter the number of full years service: "))

record.append((full_name, job_title, full_time, "%.2f" % hourly_rate, number_years))

1 个答案:

答案 0 :(得分:1)

鉴于名称是记录中的第一个元素,必须针对元组的第一个元素对名称进行任何检查。

以前你有:

record = [n for n in record if delete in record]

这里的第一个问题是你必须在你的情况下检查n而不是record

record = [n for n in record if delete in n]

下一个问题是,如果在其中找到delete,则只会在列表中添加记录。 看起来你想要反过来:

record = [n for n in record if delete not in n]
                                      ^^^

现在这本身不起作用,因为delete是一个字符串而n在这里是tuple,所以我们必须将它与第一个修复结合起来。然后我们得到:

record = [n for n in record if delete not in n[0]]

然而,我要注意的一件事是,如果您只使用员工姓名作为索引,那么使用员工姓名作为键而其他信息作为值的字典可能更清晰/更容易。鉴于字典是键和值之间的关联映射,您的问题正是我建议更改您的数据结构。