python - python中嵌套循环的范围规则
问题描述
def temp():
temparray = ['a','b']
temparray_2 = ['c','d','e']
for i in temparray:
print('i:' + str(i))
for i in temparray_2:
print('first: ' + str(i))
print('Second: ' + str(i))
print('final: ' + str(i))
为什么上面的代码输出如下?变量 i 似乎被内部循环中最后分配的任何内容覆盖。python 不遵守 Java 或 C 之类的范围规则吗?
i:a
first: c
first: d
first: e
Second: e
i:b
first: c
first: d
first: e
Second: e
final: e
解决方案
与任何函数局部赋值一样,循环索引在循环出现的整个函数的范围内。循环本身不会创建新范围。for
for
推荐阅读
- javascript - 我应该在哪里将图像存储为 ArrayBuffer
- redirect - Stripe 重定向到我的 SPA 会丢失所有状态
- excel - 如何使用 VBA 宏将 excel 表值转换为用逗号和单引号分隔的值字符串?
- jenkins - 如何在 Jenkins 中一次只执行 1 个作业构建
- python - GraphViz 的可执行文件在 python 中未找到错误
- github - 支持 GitHub 发布的 AWS Codebuild
- phpexcel - 用phpExcel导出excel多行
- python-3.x - 如何告诉pytesseract有一定数量的数字
- firebase - Firebase 团队用户创建但不发送通知的权限
- python - 在我的示例中,如何用 Pillow 替换 scipy.misc.imresize?