开发者

removing elements incrementally from a list

开发者 https://www.devze.com 2022-12-31 12:36 出处:网络
I\'ve a list of float numbers and I would like to delete incrementally a set of elements in a 开发者_运维问答given range of indexes, sth. like:

I've a list of float numbers and I would like to delete incrementally a set of elements in a 开发者_运维问答given range of indexes, sth. like:

for j in range(beginIndex, endIndex+1):
   print ("remove [%d] => val: %g" % (j, myList[j]))
   del myList[j]

However, since I'm iterating over the same list, the indexes (range) are not valid any more for the new list. Does anybody has some suggestions on how to delete the elements properly?

Best wishes


Do you really need to remove them incrementaly?

If not, you can do it like this:

del myList[beginIndex:endIndex+1]


You can iterate from the end to beginning of the sequence:

for j in range(endIndex, beginIndex-1, -1):
    print ("remove [%d] => val: %g" % (j, myList[j]))
    del myList[j]


Something like this?

>>> list1 = [1,2,3,4,5,6]
>>> start, end = 2, 4
>>> list1[:start] + list1[end:]
[1, 2, 5, 6]
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号