python循环嵌套的内循环控制变量与外循环变量可以同名_嵌套循环中不同值的相同变量名。...

我想你可以将上面表达式中的内部循环大致翻译为:for e in x:

ee = iter(e)

try:

e = next(ee)

while True

print e

e = next(ee)

except StopIteration

pass

注意,这里的关键在于语句:for e in ...,...通过iterator protocol转换为迭代器。您实际迭代的对象是一个独立的对象,与您最初给它的e不同。因为它是一个单独的对象(在当前作用域中与它的名称分开存储以允许它被迭代),所以在当前作用域中将一个新变量绑定到该名称是没有问题的——也许我应该说除了它使代码很难理解外,没有其他问题。在

实际上,这和你做这件事没有问题的原因是一样的:

^{pr2}$

这里还有几个问题需要考虑:x = [1,2,3,4]

for a in x:

print a

next(a) #Raises an error because lists aren't iterators!

现在是一个很少使用(但有时是必要的)成语:x = [1,2,3,4]

y = iter(x) #create an iterator from the list x

for a in y:

print a

#This next line is OK.

#We also consume the next value in the loop since `iter(y)` returns `y`!

#In fact, This is the easiest way to get a handle on the object you're

#actually iterating over.

next(y)

最后:x = [1,2,3,4]

y = iter(x) #create an iterator from the list x

for a in y:

print a

#This effectively does nothing to your loop because you're rebinding

#a local variable -- You're not actually changing the iterator you're

#iterating over, just as `A = 'bar'` doesn't change the value of

#the variable `c` in one of the previous examples.

y = iter(range(10))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值