为什么我不能对相同的数据进行两次迭代? [英] Why can't I iterate twice over the same data?

查看:139
本文介绍了为什么我不能对相同的数据进行两次迭代?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

老实说,我在这里有些困惑,为什么我不能对相同的数据进行两次迭代?

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?

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

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

If we are traversing some data using a 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.

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:

data = list(db[3])

But if there are many elements, it's a better idea to create independent iterators using tee():

import itertools
it1, it2 = itertools.tee(db[3], n=2) # create as many as needed

Now we can loop over each one in turn:

for e in it1:
    print("doing this one time")

for e in it2:
    print("doing this two times")

这篇关于为什么我不能对相同的数据进行两次迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆