问题在for循环中删除列表项(python) [英] problem Deleting list items in a for loop (python)

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

问题描述

可能重复:
在Python中进行迭代时从列表中删除项目

Possible Duplicate:
Remove items from a list while iterating in 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)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆