使用用户输入修改列表,按索引选择项目

时间:2018-04-23 18:24:15

标签: python list

如何通过索引从此列表中选择一个项目并将其修改回列表并进行更新?

mylist = ['CHECK EMAIL', 'OPEN PROJECT', 'PRIORITIZE PROJECT']
i = 1
for list in mylist:
    print i, list
    i = i + 1

while True:


    elif ToDo == 'R':
        index = raw_input('What would you like to remove from the list?').upper()

        if index in mylist:
            mylist.remove(index)
            print "It has been removed. What would you like to do now?\n"
            print "Your New ToDoList :"
            print"-----------"
            i = 1
            for index in mylist:
                print i, list
                i = i + 1
        else:
            print "THAT doesn't exist in this list!! Try again!"

2 个答案:

答案 0 :(得分:0)

该问题的两个部分:

"我如何通过它的索引"

从此列表中选择一个项目

假设index是索引,而mylist是列表,则可以使用mylist[index]来实现。显然,index必须是(至少)一个整数。在您当前的代码中,它来自raw_input,它返回一个字符串。因此,使用例如index = int(index)将该字符串转换为整数。

"并通过更新将其修改回列表?"

假设x包含新值:mylist[index] = x

如果您想首先删除该项目,请继续使用mylist.remove(index),如果您想在同一位置插入新内容,请使用mylist.insert(index, x)

更多关于列表:https://docs.python.org/2/tutorial/datastructures.html(Python 2,因为您使用的是print i, list而不是print(i, list)。我建议您转到Python 3。

答案 1 :(得分:0)

请尝试以下代码..我希望它符合您的要求。

mylist = ['检查电子邮件','打开项目','优先项目'] i = 1

列表中的列表:     打印(I,列表)     i = i + 1

而mylist:

index = int(input('What would you like to remove from the list? \n'))
print(index)

if index <= len(mylist):
    del mylist[index - 1]
    print("It has been removed. What would you like to do now?\n")
    print ("Your New ToDoList :")
    print("-----------")
    i = 1
    for index in mylist:
        print(i,index)
        i = i + 1
else:
    print("THAT doesn't exist in this list!! Try again!")