皮林特说
W: 6: Using possibly undefined loop variable 'n'
...使用此代码:
iterator = (i*i for i in range(100) if i % 3 == 0)
for n, i in enumerate(iterator):
do_something(i)
print n
因为如果迭代器为空(例如[]
)n
是未定义的,ok。但我喜欢这个把戏。如何安全使用?
我认为使用 len(list(iterator))
不是最佳选择,因为您必须执行两个循环。我认为使用计数器并递增它不是很 pythonic。
最佳答案
您是否考虑过在运行循环之前仅将 n
初始化为 None
?
关于python - 皮林特 : Using possibly undefined loop variable 'n' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2344315/