Why does a range have the function “count”?

丶灬走出姿态 提交于 2020-11-28 09:35:46

问题


Unless I'm mistaken, a range can only include unique numbers. So, a number could be in it or not.

I guess only if we want to pass a range as one of many accepted types (dynamic) to some function would it make sense.

However, it seems like if it would go over the whole range to count a number it would be very inefficient.

I tried to time it compared to "in", but on my machine it seems they have the same timing. Can that be right?


回答1:


Because range() objects conform to the Sequence ABC, and that ABC has a .count() method.

In other words, it is there for completeness sake, so that the object qualifies as a sequence.

It doesn't have to go across the whole range as it is easy enough to calculate if the number is part of the sequence, see Why is `1000000000000000 in range(1000000000000001)` so fast?



来源:https://stackoverflow.com/questions/30311007/why-does-a-range-have-the-function-count

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!