Python:如何从列表中删除要在程序中选择作为输入的项目?

时间:2017-07-17 19:54:16

标签: python list input

Tasks = []

while True:
    linea1 = raw_input("Add, remove or print task ").split()
    if not linea1:
        break;

    AddTask = str (linea1[0])
    if linea1[0] == "add_task":
        Tasks.append(linea1)
    elif linea1[0] == "remove_task":
        del (Tasks[x])
    elif linea1[0] == "view_tasks":
        for index in range(len(Tasks)):  
            print("[{}] : {}".format(index, Tasks[index]))
    else:
        break;

添加,删除或打印任务remove_task

TypeError:列表索引必须是整数,而不是列表

1 个答案:

答案 0 :(得分:0)

您想要remove_task删除最后一个元素吗?如果是这样,你只需要进行一些小修改:

Tasks = []

while True:
    linea1 = raw_input("Add, remove or print task ").split()
    if not linea1:
        break;

    AddTask = str (linea1[0])
    if linea1[0] == "add_task":
        Tasks.append(linea1)
    elif linea1[0] == "remove_task":
        del (Tasks[len(Tasks) - 1])
    elif linea1[0] == "view_tasks":
        for index in range(len(Tasks)):  
            print("[{}] : {}".format(index, Tasks[index]))
    else:
        break;