for循环忽略了我的列表的一些元素 [英] for loop ignores some elements of my list

查看:125
本文介绍了for循环忽略了我的列表的一些元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:


我想删除列表中晚于给定日期的所有日期。我看不出为什么我的方法只删除列表中的一些项目。这是我得到的:

pre $ import datetime
import numpy as np
import os

list_dates = [datetime.date(2012,1,3),datetime.date(2012,1,1),datetime.date(2012,1,5),datetime.date(2013,1,3) ),datetime.date(2013,1,1)]

用于list_dates中的项目:
if item> datetime.date(2012,1,1):
list_dates.remove(item)

print list_dates

返回

  [datetime.date(2012,1,1),datetime.date (2013,1,3)] 


是正确的,你不能修改列表,而你迭代通过相同的。

  list_dates = [datetime.date(2012,1,3) ),datetime.date(2012,1,1),datetime.date(2012,1,5),datetime.date(2013,1,3),datetime.date(2013,1,1)] 

为list_dates中的项目:
if item< datetime.date(2012,1,1):
new_list_dates.add(item); / /移动这个项目(你想保留)到一个新的列表。

print new_list_dates


Possible Duplicate:
Remove items from a list while iterating in Python

I want to remove all the dates in a list which are later than a given date. I can't see why my method only removes some items of the list. Here's what I've got:

import datetime
import numpy as np
import os

list_dates = [datetime.date(2012,1,3), datetime.date(2012,1,1), datetime.date(2012,1,5), datetime.date(2013,1,3), datetime.date(2013,1,1)]

for item in list_dates:
    if item > datetime.date(2012,1,1):
        list_dates.remove(item)

print list_dates

returns

[datetime.date(2012, 1, 1), datetime.date(2013, 1, 3)]

解决方案

James and GWW are right, you cant modify the list while you are iterating through the same. Instead copy the items which you want to keep to a new list.

list_dates = [datetime.date(2012,1,3), datetime.date(2012,1,1), datetime.date(2012,1,5), datetime.date(2013,1,3), datetime.date(2013,1,1)]        

for item in list_dates:
            if item < datetime.date(2012,1,1):
                new_list_dates.add(item); // move this item (which you want to keep) to a new list.

    print new_list_dates

这篇关于for循环忽略了我的列表的一些元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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