简体   繁体   English

如何在Python中的循环中更改迭代变量的值?

[英]How can you change the value of the iterating variable in a loop in Python?

I have something like this : 我有这样的事情:

#tokens is a list of a few words
for i in xrange(0,len(tokens)):
    #some code to modify the contents of token[i]
    if tokens[i] == some value:
        del tokens[i]

Now if the array has 7 elements, i goes from 0 to 6, and in the middle of the processing if I delete an array element, then the new size becomes 6 but the loop will still run till i=6 and access tokens[6] and throw an error because the new size is 6 ie max index is 5. 现在,如果数组有7个元素,我从0变为6,并且在处理过程中,如果删除数组元素,则新大小变为6,但循环仍将运行直到i = 6并访问令牌[6] ]并抛出错误,因为新大小为6,即最大索引为5。

I guess I can use a while loop with some condition like: 我想我可以在某些情况下使用while循环:

while(i<currMaxIndex)

where I can dynamically change currMaxIndex. 在这里我可以动态更改currMaxIndex。

But I was just really curious to know if there was any way to alter i in the for loop itself. 但是我真的很好奇,想知道是否有任何方法可以改变for循环本身。

If absolutely MUST know, this is my code: 如果绝对必须知道,这是我的代码:

for i in xrange(0,len(tokens)):
            tokens[i]=tokens[i].translate(string.maketrans("",""),string.punctuation)
            if tokens[i]=='':
                del tokens[i]

I would do this: 我会这样做:

def myfilter(token):
    return token.translate(None, string.punctuation)   

tokens = filter(None, map(myfilter, tokens))

If the logic is too complicated to do it through the map / filter, it is recommended to use this approach: 如果逻辑过于复杂,无法通过map / filter进行操作,则建议使用以下方法:

for item in items[:]: # [:] copies the list
    if condition(item):
        items.remove(item)

len(tokens) is computed when you create the xrange object, so if you are deleting elements from the list, tokens[i] may not exist or may have a value that is different from what you'd expect. len(tokens)是在创建xrange对象时计算的,因此,如果要从列表中删除元素, tokens[i]可能不存在,或者其值可能与期望的值不同。

For example: 例如:

>>> a = [1, 2, 3]
>>> a[1]
2
>>> del a[1]
>>> a[1]
3

Instead of modifying the original list, create a new one: 无需修改原始列表,而是创建一个新列表:

new_tokens = []

for token in tokens:
    translated = token.translate(None, string.punctuation)

    if translated:
        new_tokens.append(translated)

Or you can filter a generator expression: 或者,您可以filter生成器表达式:

new_tokens = filter(None, (token.translate(None, string.punctuation) for token in tokens))

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

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