简体   繁体   English

从列表中逐步删除元素

[英]removing elements incrementally from a list

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. 我有一个浮点数列表,我想在给定的索引范围内逐步删除一组元素,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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM