简体   繁体   English

是否有一种pythonic方法来进行带索引的while循环?

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

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? 有没有更多的Pythonic方法来编写下面的代码,以便它迭代某些条件但是还保留了迭代的索引?

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

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)
    ]

You are always increasing i so just use range: 你总是在增加i所以只使用范围:

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

Have you ever heard the old saying "Give a man a hammer and suddenly all his problems look like nails"? 你有没有听过这句老话:“给一个人一把锤子,突然他的所有问题看起来都像指甲”? The while loop is not a hammer. while循环不是锤子。

Why use a while loop at all? 为什么要使用while循环? If I am correct your problem can be stated without reference to them as "produce a list of the locations of all suffixes of text which match a given trie ". 如果我是正确的,你可以在不引用它们的情况下陈述你的问题,因为“产生一个与给定trie相匹配的所有text后缀的位置列表”。

This can be written as a list comprehension: 这可以写成列表理解:

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

I added a return as there is little point in computing a value only to retain no reference to it. 我添加了一个return因为在计算值时没有什么意义,只是为了不保留对它的引用。

enumerate() is a great way to iterate over something and get an index as well. enumerate()是迭代某些东西并获得索引的好方法。 It returns an iterable that yields tuples of (counter, value) 它返回一个迭代,产生(计数器,值)的元组

https://docs.python.org/2/library/functions.html#enumerate https://docs.python.org/2/library/functions.html#enumerate

From the docs: 来自文档:

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]

So you can use it in a for loop really easily: 所以你可以很容易地在for循环中使用它:

for (i,season) in enumerate(seasons):
     print "{} {}".format(i,season)

prints: 打印:

0 Spring
1 Summer
2 Fall
3 Winer

enumerate is often used for tracking the index in a for loop. enumerate通常用于跟踪for循环中的索引。 Here is an example of how to use it. 以下是如何使用它的示例。

for i, elem in enumerate("abc"):
    print(i, elem)

0 a
1 b
2 c

In your example, you aren't using the elem as in the above case, so enumerate may not be the best solution. 在您的示例中,您没有像上面那样使用elem ,因此enumerate可能不是最佳解决方案。 You should probably either try using range or stick with the while loop you already have. 您应该尝试使用range或坚持使用已有的while循环。

for location in range(len(text)):
    if PrefixTrieMatching(text[location:], trie):
        match_locations.append(location)

I wouldn't necessarily use this, but itertools.count() is [1, 2, 3, ...] . 我不一定会使用它,但是itertools.count()[1, 2, 3, ...]

import itertools
for i in itertools.count():
    ...

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

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