Getting number of elements in an iterator in Pytho

2019-01-03 05:48发布

Is there an efficient way to know how many elements are in an iterator in Python, in general, without iterating through each and counting?

15条回答
劫难
2楼-- · 2019-01-03 06:51

It's common practice to put this type of information in the file header, and for pysam to give you access to this. I don't know the format, but have you checked the API?

As others have said, you can't know the length from the iterator.

查看更多
倾城 Initia
3楼-- · 2019-01-03 06:51

This is against the very definition of an iterator, which is a pointer to an object, plus information about how to get to the next object.

An iterator does not know how many more times it will be able to iterate until terminating. This could be infinite, so infinity might be your answer.

查看更多
再贱就再见
4楼-- · 2019-01-03 06:54

There are two ways to get the length of "something" on a computer.

The first way is to store a count - this requires anything that touches the file/data to modify it (or a class that only exposes interfaces -- but it boils down to the same thing).

The other way is to iterate over it and count how big it is.

查看更多
登录 后发表回答