问题在for循环中删除列表项

问题在for循环中删除列表项

本文介绍了问题在for循环中删除列表项(python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我遇到了一个问题,在遍历python中的列表时似乎无法删除项目,这就是我得到的:如果用户在for循环中被问到要删除的问题时输入n或N,则应该删除标题,问题是当所有操作完成后,所有项目都仍然存在并且没有任何内容被删除...

Hi im having a problem i cant seem to delete items whilst iterating through a list in python,Here is what i've got: a title should be removed if a user Inputs n or N when asked the question to delete in the for loop, the problem is that when its all done the items are all still there and none have been removed...

    titles_list = ["English", "Math", "History", "IT", "Biology", "Spanish"]

    for title in titles_list:
        print "Do you want to keep the title:", title , "\n or Delete it ? Input Y for keep, N for Delete "
        Question = raw_input()
        if str(Question.upper) == "N":
            titles_list.remove(title)

print titles_list

推荐答案

以下代码将解决您的问题.您必须遍历列表的副本.您无法从要迭代的列表中删除项目.

The below code will fix your issue. You have to iterate over a copy of the list. You can't remove items from the list you are iterating over.

import copy

def main():
    titles_list = ["English", "Math", "History", "IT", "Biology", "Spanish"]
    titles_list_orig = copy.deepcopy(titles_list)

    for title in titles_list_orig:
        print "Do you want to keep the title:", title , "\n or Delete it? Input Y for keep, N for Delete "
        Question = raw_input()
        if str(Question.upper()) == "N":
            titles_list.remove(title)

    print titles_list

这篇关于问题在for循环中删除列表项(python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 00:32