例如,运行 macOS Catalina v10.15,我/usr/bin/python提供了 Python 2.7.16 和/usr/bin/python3Python 3.7.3。
在 macOS Big Sur v11.0 中,Apple 终于放弃了 Python 2 并让 Python 3 成为默认版本吗?
如果循环遍历list/tuple/sequence,则可以len(...)用来推断循环执行的次数.但是当循环遍历迭代器时,你不能.
[ 为清晰起见更新:我正在考虑一次性使用有限迭代器,我想对项目进行计算并同时计算它们.]
我目前使用显式计数器变量,如下例所示:
def some_function(some_argument):
pass
some_iterator = iter("Hello world")
count = 0
for value in some_iterator:
some_function(value)
count += 1
print("Looped %i times" % count)
Run Code Online (Sandbox Code Playgroud)
鉴于有11个字符"Hello world",这里的预期输出是:
Looped 11 times
Run Code Online (Sandbox Code Playgroud)
我也考虑过这个较短的替代方案,enumerate(...)但我不觉得这很清楚:
def some_function(some_argument):
pass
some_iterator = iter("Hello world")
count = 0 # Added for special case, see note below
for count, value in enumerate(some_iterator, start=1):
some_function(value)
print("Looped %i times" % count)
Run Code Online (Sandbox Code Playgroud)
[ 更新供参考:@mata发现,如果迭代器为空,那么第二个例子在最初编写时会失败.插入count = 0解决了这个,或者我们可以使用该for ... else ... …