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