本文介绍了使用Python 2.7获取循环内部(非无限)迭代器的长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一些使用 itertools.imap 生成的迭代器,我想如果有一种方法可以访问 for-loop 我用来遍历元素。



我可以肯定的是,迭代器不会生成无限量的数据。

另外,因为循环的信息是从查询到数据库的,所以我可以从那里得到信息的长度,但是我使用的函数必须返回一个迭代器。



我想到了一些选择:

  def iterator_function(some,arguments,that,I,need):
query_result = query()
return_iterator = itertools.imap(
mapping_function,
query_result

return return_iterator

因为我不行改变返回的迭代器,我想到了一些(真的很丑),如:

query_result = query()
query_size = len(query_result)
$ b return_iterator = itertools .imap(
lambda item:(mapping_function(item),query_size),
query_result


return return_iterator

但是我不太喜欢这个选项,我在想Python是否有办法从循环中获取迭代器大小在迭代器中,如下所示:
$ b

for iterator()中的项目:
print item.iterator_length()
#做其他的东西

甚至类似于:

打印iterator.length()#或iterator() 。长度()???

谢谢!

解决方案数据库,我可以从那里得到信息的长度,但$ b $我使用的函数必须返回一个迭代器。

假设你有一个好的数据库,在那里进行计数。怀疑python中的任何解决方案都会更快更清洁。


I'm working with some iterator generated using itertools.imap, and I was thinking if there is a way to access the iterator length inside the for-loop that I use to loop over the elements.

What I can say for sure is that the iterator doesn't generate an infinite amount of data.

Also, because the information I'm looping are from a query to a database, I can get the length of the information from there, but the function I'm using has to return an iterator.

I thought of some options:

def iterator_function(some, arguments, that, I, need):
    query_result = query()
    return_iterator = itertools.imap(
        mapping_function,
        query_result
    )
    return return_iterator

Because I cannot change the returned iterator, I thought of something (really ugly) like:

query_result = query()
query_size = len(query_result)

return_iterator = itertools.imap(
    lambda item: (mapping_function(item), query_size),
    query_result
)

return return_iterator

But I don't really like this option, and I was thinking if there is a way, in Python, to get the iterator size from inside the loop over the iterator, something like:

for item in iterator():
    print item.iterator_length()
    # do other stuff

Or even something like:

for item in iterator():
    print iterator.length() # or iterator().length()???

Thanks!

解决方案

Assuming you have a good database, do the count there. Doubt any solution in python will be faster/cleaner.

这篇关于使用Python 2.7获取循环内部(非无限)迭代器的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 10:30
查看更多