python内置高阶函数 zip_2021-01-18 python 中的内置高级函数

[python 中的内置高级函数]

1.map(function,iterable)

map是把迭代对象依次进行函数运算,并返回。

例子:

054c7c5c7b2f

image

map返回的十分map对象,需要list()函数转化。

2.exec()函数

执行储存在字符串或文件中的 Python 语句,相比于 eval,exec可以执行更复杂的 Python 代码。

Execute the given source in the context of globals and locals. 在全局变量和局部变量上下文中执行给定的源。

The source may be a string representing one or more Python statements or a code object as returned by compile().

The globals must be a dictionary and locals can be any mapping, defaulting to the current globals and locals.

全局变量必须是一个字典类型,局部变量可以是任何映射

If only globals is given, locals defaults to it.

如果仅仅给订全局变量,局部变量也默认是它。

执行单行语句

exec('print("Hello World")')

执行多行语句

exec("""

for i in range(10):

print(i,end=",")

""")

运行结果

Hello World

0,1,2,3,4,5,6,7,8,9,

x = 10 # global

expr = """

z = 30

sum = x + y + z

print(sum)

print("x= ",x)

print("y= ",y)

print("z= ",z)

"""

def func():

y = 20 #局部变量

exec(expr)

exec(expr, {'x': 1, 'y': 2})

exec(expr, {'x': 1, 'y': 2}, {'y': 3, 'z': 4})

# python寻找变量值的顺寻,LEGB

# L->Local 局部变量

# E->Enclosing function locals 函数内空间变量

# G->global 全局变量

# B-> bulltlins

# 局部变量———闭包空间———全局变量———内建模块

func()

结果是:

60

x= 10 ,y= 20,z= 30

33

x= 1 ,y= 2, z= 30

34

x= 1 ,y= 3 ,z= 30

python 中寻找变量顺序:

LEGB

L-Local

E->enclose function local

G->global

B->bultins

局部变量->函数体内变量-》全局变量-》内置函数

3.zip()函数

zip() is a built-in Python function that gives us an iterator of tuples.

for i in zip([1,2,3],['a','b','c']):

print(i)

结果:

(1,'a')

(2, 'b')

(3, 'c')

054c7c5c7b2f

image

054c7c5c7b2f

image

zip将可迭代对象作为参数,将对象中对应的元素打包组成一个个元组,然后返回这些元组组成的列表。

而zip(*c)则是将原来的组成的元组还原成原来的对象。

4.repr()函数

repr() 函数将对象转化为供解释器读取的形式。返回一个对象的 string 格式。

054c7c5c7b2f

image

054c7c5c7b2f

image

看以看出来当输入的是”123“,则str()函数输出的是123,而repr输出的是”123“.

str()不保留原来的类型,而repr则保留数据类型。

每天进步一点

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值