Python:迭代时将元素添加到列表中 [英] Python: Adding element to list while iterating

查看:820
本文介绍了Python:迭代时将元素添加到列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在迭代列表时不允许删除元素,但允许在迭代时将元素添加到python列表中。这是一个例子:

I know that it is not allowed to remove elements while iterating a list, but is it allowed to add elements to a python list while iterating. Here is an example:

    for a in myarr:
      if somecond(a):
          myarr.append(newObj())

我在我的代码中尝试了这个并且似乎工作正常,但是我不知道是不是因为我很幸运,并且它将来会在某个时候破裂?

I have tried this in my code and it seems to works fine, however i dont know if its because i am just lucky and that it will break at some point in the future?

编辑:我不想复制列表,因为myarr是巨大的,因此它会太慢。另外我需要用somecond()来检查附加的对象。

i prefer not to copy the list since "myarr" is huge, and therefore it would be too slow. Also i need to check the appended objects with "somecond()".

编辑:在某些时候somecond(a)将是假的,所以不可能无限循环。

At some point "somecond(a)" will be false, so there can not be an infinite loop.

编辑:有人问过somecond()函数。 myarr中的每个对象都有一个大小,每次somecond(a)为真,并且新对象被附加到列表中,新对象的大小将小于a。 somecond()有一个epsilon表示小对象可以如何,如果它们太小则会返回false

Someone asked about the "somecond()" function. Each object in myarr has a size, and each time "somecond(a)" is true and a new object is appended to the list, the new object will have a size smaller than a. "somecond()" has an epsilon for how small objects can be and if they are too small it will return "false"

推荐答案

您可以使用itertools中的 islice 在列表的较小部分上创建迭代器。然后你可以在不影响你迭代的项目的情况下将条目附加到列表中:

You could use the islice from itertools to create an iterator over a smaller portion of the list. Then you can append entries to the list without impacting the items you're iterating over:

islice( myarr, 0, len(myarr)-1 )

更好的是,你甚至不必遍历所有元素。您可以增加步长。

Even better, you don't even have to iterate over all the elements. You can increment a step size.

这篇关于Python:迭代时将元素添加到列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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