有没有一个pythonic的方法来做一个索引whileloop?

2024-10-04 11:25:19 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有一种更具python风格的方法来编写下面的代码,以便它在某些条件上进行迭代,同时保留迭代的索引?你知道吗

def TrieMatching(text, trie):
    match_locations = []
    location = 0
    while text:
        if PrefixTrieMatching(text, trie):
            match_locations.append(location)
        text = text[1:]
        location += 1

Tags: 方法代码textif风格defmatchlocation
3条回答

我总是喜欢列表理解。你知道吗

def TrieMatching(text, trie):
    match_locations = [
        location
        for location in range(len(text))
        if PrefixTrieMatch(text[location:],trie)
    ]

你有没有听过一句老话“给一个人一把锤子,突然他所有的问题都像钉子一样”?while循环不是锤子。你知道吗

为什么要使用while循环?如果我是对的,你的问题可以不用参考它们就说成“产生一个匹配给定的trietext的所有后缀的位置列表”。你知道吗

这可以写成一个列表:

def TrieMatching(text, trie):
   return [l for l in range(len(text)) if PrefixTrieMatching(text[l:], trie)]

我添加了一个return,因为计算一个值并没有什么意义,只是为了不保留对它的引用。你知道吗

您总是在增加i,所以只需使用范围:

def TrieMatching(text, trie):
    match_locations = []
    for i in range(len(text)):
        if PrefixTrieMatching(text[i:], trie):
            match_locations.append(i)

相关问题 更多 >