为什么我不能对相同的数据进行两次迭代? [英] Why can't I iterate twice over the same data?
问题描述
老实说,我在这里有些困惑,为什么我不能对相同的数据进行两次迭代?
def _view(self,dbName):
db = self.dictDatabases[dbName]
data = db[3]
for row in data:
print("doing this one time")
for row in data:
print("doing this two times")
这将多次打印执行一次"(因为数据有几行),但是根本不会打印两次执行" ...
我第一次遍历数据工作正常,但是第二次当我运行最后一个列表针对数据中的行"时,此操作什么都不会返回……因此一次执行它却不能两次……?>
仅供参考-数据是一个csv.reader对象(如果是原因)...
这是因为data
是一个迭代器,您只能使用一次迭代器.例如:
lst = [1, 2, 3]
it = iter(lst)
next(it)
=> 1
next(it)
=> 2
next(it)
=> 3
next(it)
=> StopIteration
如果我们使用for
循环遍历某些数据,则最后一个StopIteration
将导致它第一次退出.如果尝试再次 对其进行迭代,则将继续获取StopIteration
异常,因为迭代器已被消耗.
现在要回答第二个问题:如果我们要做需要多次遍历迭代器怎么办?一个简单的解决方案是用元素创建一个列表,我们可以根据需要遍历它多次.只要列表中的元素很少,就可以了:
data = list(db[3])
但是,如果元素很多,最好使用 Honestly I am a little confused here, why can't I iterate twice over the same data? This will print out "doing this one time" a few times (as data has a few rows), however it will NOT print out "doing this two times" at all ... The first time I iterate over data works fine, but the second time when I run the last list "for row in data" this returns nothing ... so executing it one time works but not twice ... ? FYI - data is a csv.reader object (in case that is the reason)... It's because If we are traversing some data using a Now for the second question: What if we do need to traverse the iterator more than once? A simple solution would be to create a list with the elements, and we can traverse it as many times as needed. This is all right as long as there are few elements in the list: But if there are many elements, it's a better idea to create independent iterators using Now we can loop over each one in turn:
这篇关于为什么我不能对相同的数据进行两次迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!def _view(self,dbName):
db = self.dictDatabases[dbName]
data = db[3]
for row in data:
print("doing this one time")
for row in data:
print("doing this two times")
data
is an iterator, an you can consume an iterator only once. For example:lst = [1, 2, 3]
it = iter(lst)
next(it)
=> 1
next(it)
=> 2
next(it)
=> 3
next(it)
=> StopIteration
for
loop, that last StopIteration
will cause it to exit the first time. If we try to iterate over it again, we'll keep getting the StopIteration
exception, because the iterator has already been consumed.data = list(db[3])
tee()
:import itertools
it1, it2 = itertools.tee(db[3], n=2) # create as many as needed
for e in it1:
print("doing this one time")
for e in it2:
print("doing this two times")