首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >遍历python列表

遍历python列表
EN

Stack Overflow用户
提问于 2017-10-06 04:18:36
回答 1查看 56关注 0票数 0

我在我的数据库中有500条记录,我正在将它们全部加载到字典元素的python列表中。

我正在调用一个方法,该方法遍历列表中的所有字典元素,并对每个记录执行一些操作。在遍历时,我注意到在遍历了一半的元素之后,逻辑退出了方法,并在下半部分重新启动。

我试着把它作为一个例子。(我无法复制确切的代码,因为这是不可能的)

例如:

代码语言:javascript
复制
def loadrec():
  reading from database and appending rows to a global list(mylist)

def myrun():
  print "****** Execution Started **********"
  for row in mylist:
    doing some operations and printing a string

if __name__=="__main__":
i=0
while (i>=0): #This never ends(to make the script run forever)
   loadrec()
   myrun()
   print "****** Execution Ended ************"



Result:


****** Execution Started **********
printed 250 records
****** Execution Ended ************


****** Execution Started **********
printed 125 records
****** Execution Ended ************


****** Execution Started **********
printed 62 records
****** Execution Ended ************

****** Execution Started **********
printed 31 records
****** Execution Ended ************

****** Execution Started **********
printed 15 records
****** Execution Ended ************

****** Execution Started **********
printed 7 records
****** Execution Ended ************

****** Execution Started **********
printed 1 record
****** Execution Ended ************

我不知道为什么每次只处理总记录的一半。但是,最后,它正在处理所有的记录。

我试过检查python列表的最大大小或内存是否有问题,但它们似乎都不是可能的场景。

会很高兴知道任何可能是什么原因。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-10-06 04:36:55

我要在黑暗中疯狂地捅一刀。

你在做这样的事情:

代码语言:javascript
复制
def myrun():
    print "****** Execution Started **********"
    for row in mylist:
        #Some processing here
        myList.remove(row)

您不能修改正在迭代的列表。这将只占每次处理列表的一半。您需要重构您的代码。如果没有你给我们展示你的代码,我甚至不会尝试去做重构。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46598205

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档