没有合适的资源?快使用搜索试试~ 我知道了~
在讲这个话题前,首先我们来看一道题: 代码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 pr
资源推荐
资源详情
资源评论
python中中for循环变量作用域及用法详解循环变量作用域及用法详解
在讲这个话题前,首先我们来看一道题:
代码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
资源评论
weixin_38593380
- 粉丝: 4
- 资源: 964
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功