如何通过索引从此列表中选择一个项目并将其修改回列表并进行更新?
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!"
答案 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!")