Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a pythonic way to do a while-loop with an index?

Tags:

python

Is there a more Pythonic way to write the code beneath, so that it iterates over some condition but also keeps an index of the iterations?

def TrieMatching(text, trie):
    match_locations = []
    location = 0
    while text:
        if PrefixTrieMatching(text, trie):
            match_locations.append(location)
        text = text[1:]
        location += 1
like image 912
jukhamil Avatar asked Jun 23 '26 15:06

jukhamil


1 Answers

I'm always fond of list comprehensions.

def TrieMatching(text, trie):
    match_locations = [
        location
        for location in range(len(text))
        if PrefixTrieMatch(text[location:],trie)
    ]
like image 150
Robᵩ Avatar answered Jun 25 '26 04:06

Robᵩ