神剑山庄资源网 Design By www.hcban.com
在讲这个话题前,首先我们来看一道题:
代码1:
def foo(): return [lambda x: x**i for i in range(1,5,2)] print([f(3) for f in foo()])
伙伴们,你们认为这里产生的结果是什么呢?我们再来看下这题的变体:
代码:2
def foo(): functions=[] for i in range(1,5,2): def inside_fun(x): return x ** i functions.append(inside_fun) return functions print([f(3) for f in foo()])
这两题的结果是一样的:都是[27,27]。我相信大部分的伙伴也都会有个疑问,为什么不是[3,27]呢?
这里的就是我们今天要说的for循环中的变量作用域,因为for循环不是一个函数体,所以for循环中的变量i的作用域其实和for循环同级,即类似下面代码
代码3:
def foo(): i=None for i in range(1,5,2): pass print(i) foo() # 结果为3,即循环结束i的最终值
另外因为python运行到代码行时才会去查找该变量的作用域,所以代码1和代码2中的i值在调用的时候为for循环最终值3,所以结果都是执行x**3。
ps:下面看下python中for循环的用法
Python for循环可以遍历任何序列的项目,如一个列表或者一个字符串。
语法模式:for iterating_var in sequence:
in 字面意思,从某个集合(列表等)里顺次取值
#遍历数字序列 the_count=[1,2,3,4,5] for number in the_count: print(f"This is count {number}") 输出结果: This is count 1 This is count 2 This is count 3 This is count 4 This is count 5 #遍历一维字符串数组 fruits=['apples','oranges','dimes','quarters'] for fruit in fruits: print(f"A fruit of type:{fruit}") 输出结果为: A fruit of type:apples A fruit of type:oranges A fruit of type:dimes A fruit of type:quarters #遍历字符串 list_python='python' for j in list_python: print(f"{j}") 输出结果为: p y t h o n #通过序列索引迭代 elements=[]#列表为空 for i in range(0,6):#012345 print(f"Adding {i} to the list.") elements.append(i)#得到elements=[0,1,2,3,4,5] #len(elements)长为6,range(len(elements))==range(6) for i in range(len(elements)): print(f"Elemnet was:{i}") 输出结果为: Adding 0 to the list. Adding 1 to the list. Adding 2 to the list. Adding 3 to the list. Adding 4 to the list. Adding 5 to the list. Elemnet was:0 Elemnet was:1 Elemnet was:2 Elemnet was:3 Elemnet was:4 Elemnet was:5
总结
以上所述是小编给大家介绍的python中for循环变量作用域及用法详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!
神剑山庄资源网 Design By www.hcban.com
神剑山庄资源网
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
神剑山庄资源网 Design By www.hcban.com
暂无python中for循环变量作用域及用法详解的评论...
更新日志
2024年09月30日
2024年09月30日
- 孙悦.1996-伙伴【正大国际】【WAV+CUE】
- 纪钧瀚《钢琴阅读时光 雨中书店聆听轻音乐》[FLAC/分轨][399.62MB]
- 证声音乐图书馆《走向自然 疗心爵士乐》[320K/MP3][87.4MB]
- 证声音乐图书馆《走向自然 疗心爵士乐》[FLAC/分轨][184.94MB]
- 陈慧娴.2018-Priscilla-Ism演唱会3CD(2024环球红馆40复刻系列)【环球】【WAV+CUE】
- 郑秀文.1999-我应该得到(国)【华纳】【WAV+CUE】
- 陈家慧.2011-钢琴酒吧2CD【龙吟唱片】【WAV+CUE】
- 证声音乐图书馆《雨季 蓝调吉他 Rainy Blues》[320K/MP3][45.01MB]
- 证声音乐图书馆《雨季 蓝调吉他 Rainy Blues》[FLAC/分轨][109.13MB]
- 赞多《序章》[320K/MP3][45.54MB]
- 许巍.2004-每一刻都是崭新的【步升大风】【WAV+CUE】
- 群星.2024-四方馆影视原声带【韶愔音乐】【FLAC分轨】
- 陈雷.1997-安锁咧【金圆唱片】【WAV+CUE】
- 关淑怡.2013-MY.FAVORITE.SK.3CD【环球】【WAV+CUE】
- Sweety.2006-花言乔语【丰华】【WAV+CUE】