2024-10-04 11:25:19 发布
网友
有没有一种更具python风格的方法来编写下面的代码,以便它在某些条件上进行迭代,同时保留迭代的索引?你知道吗
def TrieMatching(text, trie): match_locations = [] location = 0 while text: if PrefixTrieMatching(text, trie): match_locations.append(location) text = text[1:] location += 1
我总是喜欢列表理解。你知道吗
def TrieMatching(text, trie): match_locations = [ location for location in range(len(text)) if PrefixTrieMatch(text[location:],trie) ]
你有没有听过一句老话“给一个人一把锤子,突然他所有的问题都像钉子一样”?while循环不是锤子。你知道吗
while
为什么要使用while循环?如果我是对的,你的问题可以不用参考它们就说成“产生一个匹配给定的trie的text的所有后缀的位置列表”。你知道吗
trie
text
这可以写成一个列表:
def TrieMatching(text, trie): return [l for l in range(len(text)) if PrefixTrieMatching(text[l:], trie)]
我添加了一个return,因为计算一个值并没有什么意义,只是为了不保留对它的引用。你知道吗
return
您总是在增加i,所以只需使用范围:
i
def TrieMatching(text, trie): match_locations = [] for i in range(len(text)): if PrefixTrieMatching(text[i:], trie): match_locations.append(i)
我总是喜欢列表理解。你知道吗
你有没有听过一句老话“给一个人一把锤子,突然他所有的问题都像钉子一样”?
while
循环不是锤子。你知道吗为什么要使用
while
循环?如果我是对的,你的问题可以不用参考它们就说成“产生一个匹配给定的trie
的text
的所有后缀的位置列表”。你知道吗这可以写成一个列表:
我添加了一个
return
,因为计算一个值并没有什么意义,只是为了不保留对它的引用。你知道吗您总是在增加
i
,所以只需使用范围:相关问题 更多 >
编程相关推荐