简体   繁体   English

Python循环中的Iter()

[英]Iter() during loop Python

I'm having trouble understanding why issup("oFB","FooBar") is returning False. 我在理解为什么issup("oFB","FooBar")返回False时遇到麻烦。 How does iter(t) behave during this loop? iter(t)在此循环期间的行为如何?

refer to this https://leetcode.com/problems/camelcase-matching/ https://leetcode.com/problems/camelcase-matching/discuss/270029/JavaC%2B%2BPython-Check-Subsequence-and-Regax 请参阅此https://leetcode.com/problems/camelcase-matching/ https://leetcode.com/problems/camelcase-matching/discuss/270029/JavaC%2B%2BPython-Check-Subsequence-and-Regax

I'm guessing iter(t) starts at "FooBar" , then goes to "ooBar" the next iteration and so forth. 我猜iter(t)"FooBar"开始,然后在下一次迭代时转到"ooBar" ,依此类推。

def issup(s, t):
    it = iter(t)
    return all(c in it for c in s)

iter(t) returns an iterator that returns all the elements of t . iter(t)返回一个迭代器,该迭代器返回t所有元素。 So it will return "F" , "o" , "o" , "B" , "a" , and "r" . 因此它将返回"F""o""o""B""a""r"

However, an iterator can only be used once; 但是,迭代器只能使用一次。 once it has returned all the elements, it will be empty. 一旦返回所有元素,它将为空。 So the first time that the generator executes c in it , it will step through the iterator until it finds a match for the value of c . 因此,生成器第一次在其中执行c in it ,它将逐步遍历迭代器,直到找到与c值匹配的位置。 When it tries to look for the next c , it will continue from where it left off the previous time. 当它尝试寻找下一个c ,它将从上次停止的地方继续。 And if any of them doesn't find a match, it will reach the end of the iterator and none of the following c in it tests will succeed. 而且,如果其中任何一个都找不到匹配项,它将到达迭代器的末尾,并且以下任何c in it测试都不会成功。

So when you do issup("oFB", "FooBar") , the first iteration finds the first o . 因此,当您执行issup("oFB", "FooBar") ,第一次迭代将找到第一个o The second iteration looks for F , but it can't be found because we're already past that element in the iterator. 第二次迭代查找F ,但找不到,因为我们已经在迭代器中超过了该元素。 At this point, all() returns False . 此时, all()返回False

Many Python errors are due to not realizing that iterators can only be stepped through once. 许多Python错误是由于没有意识到迭代器只能一步步完成。 Eg something like this: 例如这样的事情:

with open("filename") as f:
    for _ in range(10):
        for line in f:
            # do stuff

f is an iterator over the lines of the file. f是文件行上的迭代器。 When you reach the end of the for line loop, there's nothing left in it, so the next iteration of for _ will not have anything to loop over. 当您到达for line循环的末尾时,其中没有任何内容,因此for _的下一次迭代将没有任何循环。 In this case you can actually fix it with f.seek(0) to rewind, but most iterators don't have something like this. 在这种情况下,您实际上可以使用f.seek(0)修复它以倒带,但是大多数迭代器没有这样的内容。 The file iterator is unusual in that it uses the state of the underlying stream, rather than keeping state of its own. file迭代器之所以与众不同,是因为它使用基础流的状态,而不是保持其自身的状态。

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

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