How can you change the value of an iteration 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 go from 0 to 6, and in the middle of processing, if I delete the element of the array, the new size becomes 6, but the loop will run until i = 6 and access the tokens [6] and give an error, because that the new size is 6, i.e. maximum index is 5.

I think I can use a while loop with some condition like:

 while(i<currMaxIndex) 

where I can dynamically change currMaxIndex.

But I was just curious to know if there is a way I can change in the for loop.

If this SHOULD NOT 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] 
+4
source share
2 answers

I would do this:

 def myfilter(token): return token.translate(None, string.punctuation) tokens = filter(None, map(myfilter, tokens)) 

If the logic is too complex to do this through a map / filter, it is recommended to use this approach:

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

len(tokens) computed when the xrange object xrange , so if you remove items from the list, tokens[i] may not exist or it may have a value other than what you expect.

For instance:

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

Instead of changing 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 express the generator:

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

Source: https://habr.com/ru/post/1438344/


All Articles