[英]Get length of a (non infinite) iterator inside it's loop using Python 2.7
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. 我正在使用使用
itertools.imap
生成的一些迭代器,并且我在考虑是否有一种方法可以访问for-loop
元素的for-loop
内的迭代器长度。
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: 但是我真的不喜欢这个选项,我在想,是否有办法在Python中从迭代器的循环内部获取迭代器的大小,例如:
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! 谢谢!
I don't know if my idea is correct but how about class generator pattern and trying to add sequence bahaviour : 我不知道我的想法是否正确,但是如何使用类生成器模式并尝试添加序列行为:
if your class represents something that has a length, don't define a
GetLength
method;如果您的类表示具有长度的内容,则不要定义
GetLength
方法; define the__len__
method and uselen(instance)
.定义
__len__
方法并使用len(instance)
。
something like this : 像这样的东西:
class firstn(object):
def __init__(self, n):
self.n = n
self.num, self.nums = 0, []
def __iter__(self):
return self
# Python 3 compatibility
def __next__(self):
return self.next()
# V------- Something like this
def __len__(self):
return self.my_length
def next(self):
if self.num < self.n:
cur, self.num = self.num, self.num+1
return cur
else:
raise StopIteration()
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.
另外,由于我循环的信息是从查询到数据库,因此我可以从那里获取信息的长度,但是我正在使用的函数必须返回一个迭代器。
Assuming you have a good database, do the count there. 假设您有一个良好的数据库,请在此进行计数。 Doubt any solution in python will be faster/cleaner.
怀疑python中的任何解决方案都会更快/更清洁。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.