python在列表里增加元素,Python:迭代时将元素添加到列表中

在Python中,直接在迭代过程中删除元素是不被允许的,但关于添加元素是否安全,答案是肯定的,前提是谨慎操作。示例代码显示了一个在满足条件时向列表添加新对象的情况。然而,这可能会导致潜在的问题,尤其是当`somecond(a)`变为False时。为避免问题,可以使用`islice`工具创建一个迭代器,只遍历部分列表,从而在不影响当前迭代的情况下添加元素。此外,考虑增加步长以减少遍历的元素数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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?

EDIT: 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()".

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

EDIT: 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"

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值