本文共 3333 字,大约阅读时间需要 11 分钟。
当一个函数的返回值是另一个函数的函数名时,只是返回该函数的内存地址,该函数的作用域不会发生改变。
name = 'winsodm'def test(): name = 'xl' print('in the test')def test1(): print('in the test1') return testres = test1()# 返回的是 test1 中的函数名,函数的作用域不会改变 lambda 关键字用于定义匿名函数。
lambda 形参:return值
lambda x: x + 1lambda x, y, z: (x + 1, y + 1, z + 1)
匿名函数使用后会自动释放内存空间。
高阶函数的定义:
def test(): name = 'xl' print('in the test')def test1(): print('in the test1') return test def test(): name = 'xl' print('in the test')def test1(): print('in the test1') return test map 函数用于将一个函数应用到可迭代对象的每个元素上。
num_l = [1, 3, 5, 2, 10, 4, 6, 9, 8]new_num_l = list(map(lambda x: x + 1, num_l))# 结果:new_num_l = [2, 4, 6, 3, 11, 5, 7, 10, 9]
num_l = [1, 3, 5, 2, 10, 4, 6, 9, 8]def add_one(x): return x + 1def map_1(func, l): new_num_l = [] for i in l: new_num_l.append(func(i)) return new_num_lnew_num_l = map_1(add_one, num_l)# 结果:new_num_l = [2, 4, 6, 3, 11, 5, 7, 10, 9]
filter 函数用于过滤可迭代对象。
name_list = ['xlc', 'hhc', 'hzzc', 'hc', 'winsdom']print(list(filter(lambda x: x.endswith('m'), name_list)))# 结果:['winsdom'] name_list = ['xlc', 'hhc', 'hzzc', 'hc', 'winsdom']def end_with(x): return x.endswith('c')def filter_1(func, array): new_name_list = [] for n in array: if not func(n): new_name_list.append(n) return new_name_listnew_name_list = filter_1(end_with, name_list)# 结果:new_name_list = ['winsdom'] reduce 函数用于将可迭代对象压缩成一个值。
from functools import reducenum_l = [1, 3, 5, 100]num = reduce(lambda x, y: x * y, num_l, 2)# 结果:num = 3000
from functools import reducenum_l = [1, 3, 5, 100]def reduce_1(func, array, init=None): if init == None: res = array.pop(0) else: res = init for i in array: res = func(res, i) return resres = reduce_1(lambda x, y: x * y, num_l, 100)# 结果:res = 3000
bool(0) # 结果:False
print(abs(-1)) # 结果:1
all 会将所有元素都取 bool 运算,只要有一个为假,结果为 False。
print(all([1, 4, '2'])) # 结果:True
any 如果有一个为真,结果为 True。
any([1, 0, '2']) # 结果:True
print(bin(3)) # 结果:0b11
print(hex(12)) # 结果:0xc
print(oct(2)) # 结果:0o2
name = '你好'print(bytes(name, encoding='utf-8')) # 结果:b'\xe4\xbd\xa0\xe5\xa5\xbd'print(bytes(name, encoding='utf-8').decode('utf-8')) # 结果:‘你好’ print(chr(93)) # 结果:]
print(dir(all)) # 结果:['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__text_signature__']
dic = {'name': 'winsdom'}dic_s = str(dic)eval(dic_s) # 可以将字符串中的数据结构提取出来express = '1 + 2 * (3 / 3 - 1) - 2'eval(express) # 可以把字符串中的表达式进行运算 print(divmod(10, 3)) # 结果:(3, 1)
isinstance(1, int) # True
print(globals()) # 打印全局变量print(locals()) # 打印局部变量