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

查看:18
本文介绍了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 work fine, however I don't know if it's 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天全站免登陆