python在匿名函数作和_python内置函数和匿名函数

楔子

在讲新知识之前,我们先来复习复习函数的基础知识。

问:函数怎么调用?

函数名()

如果你们这么说。。。那你们就对了!好了记住这个事儿别给忘记了,咱们继续谈下一话题。。。

来你们在自己的环境里打印一下自己的名字。

你们是怎么打的呀?

是不是print('xxx'),好了,现在你们结合我刚刚说的函数的调用方法,你有没有什么发现?

我们就猜,print有没有可能是一个函数?

但是没有人实现它啊。。。它怎么就能用了呢?

早在我们“初识函数”的时候是不是就是用len()引出的?

那现在我们也知道len()也是一个函数,也没人实现,它好像就自己能用了。。。

之前老师给你讲你可以这样用你就用了,那你有没有想过像这样直接拿来就能用的函数到底有多少?

内置函数

接下来,我们就一起来看看python里的内置函数。截止到python版本3.6.2,现在python一共为我们提供了68个内置函数。它们就是python提供给你直接可以拿来使用的所有函数。这些函数有些我们已经用过了,有些我们还没用到过,还有一些是被封印了,必须等我们学了新知识才能解开封印的。那今天我们就一起来认识一下python的内置函数。这么多函数,我们该从何学起呢?

上面就是内置函数的表,68个函数都在这儿了。这个表的顺序是按照首字母的排列顺序来的,你会发现都混乱的堆在一起。比如,oct和bin和hex都是做进制换算的,但是却被写在了三个地方。。。这样非常不利于大家归纳和学习。那我把这些函数分成了6大类。你看下面这张图,你猜咱们今天会学哪几大类呀?

我猜你们都猜对了。我们今天就要学习用粉红色标注出来的这四大块——56个方法。还有12个方法欠着怎么办呢?我们讲完面向对象这剩下的12个会在两周之内陆续还给你们的,我保证(认真脸)。那这样,我们今天就主要关注我们要学习的这56个方法。

那要学的一共4块,咱们从哪儿开始学起呢?

作用域相关

基于字典的形式获取局部变量和全局变量

globals()——获取全局变量的字典

locals()——获取执行本方法所在命名空间内的局部变量的字典

注意:与global和 nonlocal 不一样

global 是定义全局变量的关键字

nonlocal 是定义局部或与之相连的上一级的变量关键字

其他

字符串类型代码的执行

内置函数——eval、exec、compile

eval()将字符串类型的代码执行并返回结果

eval('print(1,23)')

# 1 23

exec()将自字符串类型的代码执行

print(exec("1+2+3+4"))

结果:None

exec("print('hello,world')")

结果:hello,world

指定blobal参数code = '''

import os

print(os.path.abspath('.'))

'''

code = '''

print(123)

a = 20

print(a)

'''

a = 10

exec(code,{'print':print},)

print(a)

compile  将字符串类型的代码编译。代码对象能够通过exec语句来执行或者eval()进行求值。

参数说明:

1. 参数source:字符串或者AST(Abstract Syntax Trees)对象。即需要动态执行的代码段。

2. 参数 filename:代码文件名称,如果不是从文件读取代码则传递一些可辨认的值。当传入了source参数时,filename参数传入空字符即可。

3. 参数model:指定编译代码的种类,可以指定为 ‘exec’,’eval’,’single’。当source中包含流程语句时,model应指定为‘exec’;当source中只包含一个简单的求值表达式,model应指定为‘eval’;当source中包含了交互式命令语句,model应指定为'single'。

#流程语句使用exec

code1 = 'for i in range(0,10): print (i)'

compile1 = compile(code1,'','exec')

exec (compile1)

>>> #简单求值表达式用eval

>>> code2 = '1 + 2 + 3 + 4'

>>> compile2 = compile(code2,'','eval')

>>> eval(compile2)

>>> #交互语句用single

>>> code3 = 'name = input("please input your name:")'

>>> compile3 = compile(code3,'','single')

>>> name #执行前name变量不存在

Traceback (most recent call last):

File "", line 1, in

name

NameError: name 'name' is not defined

>>> exec(compile3) #执行时显示交互命令,提示输入

please input your name:'pythoner'

>>> name #执行后name变量有值

"'pythoner'"

# exec 和eval 都可以执行字符串类型的代码

# eval和返回值--有结果的简单计算

# exec 没有返回值---简单流程控制

# eval 只能用在你明确知道你要执行的代码是什么

输入输出相关:

input() 输入

s = input("请输入内容 : ")  #输入的内容赋值给s变量

print(s)  #输入什么打印什么。数据类型是str

print() 输出

def print(self, *args, sep=' ', end='\n', file=None): # known special case of print

"""

print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

file:  默认是输出到屏幕,如果设置为文件句柄,输出到文件

sep:   打印多个值之间的分隔符,默认为空格

end:   每一次打印的结尾,默认为换行符

flush: 立即把内容输出到流文件,不作缓存

"""

print('我们的祖国是花园',sep='') #指定输出的结束符

# 结果为:

# 我们的祖国是花园

# Process finished with exit code 0

# 如不指定,输出的结果为:

我们的祖国是花园

Process finished with exit code 0

print(1,2,3,sep='|') #指定输出多个值之间的分隔符

f = open('file','w')

print('aaaa',file=f) #打印aaaa到file文件中

file关键字说明

f = open('tmp_file','w')

print(123,456,sep=',',file = f,flush=True)

打印进度条

import time

for i in range(0,101,2):

time.sleep(0.1)

char_num = i//2      #打印多少个'*'

per_str = '\r%s%% : %s\n' % (i, '*' * char_num) if i == 100 else '\r%s%% : %s'%(i,'*'*char_num)

print(per_str,end='', flush=True)

#小越越  : \r 可以把光标移动到行首但不换行

数据类型相关:

type(o) 返回变量o的数据类型

内存相关:

id(o) o是参数,返回一个变量的内存地址

hash(o) o是参数,返回一个可hash变量的哈希值,不可hash的变量被hash之后会报错。

hash值实例

t = (1, 2, 3)

l = [1, 2, 3]

print(hash(t)) #可hash

结果:-2022708474

# print(hash(l)) #会报错

'''

结果:

TypeError: unhashable type: 'list'

'''

hash函数会根据一个内部的算法对当前可hash变量进行处理,返回一个int数字。每一次执行程序,内容相同的变量hash值在这一次执行过程中不会发生改变。

文件操作相关

open()  打开一个文件,返回一个文件操作符(文件句柄)

操作文件的模式有r,w,a,r+,w+,a+ 共6种,每一种方式都可以用二进制的形式操作(rb,wb,ab,rb+,wb+,ab+)

可以用encoding指定编码.

f.writable 检测是否可以写

f.readable 检测是否可以读

模块操作相关

__import__导入一个模块

导入模块

import time

也可以以下这中模式打开

os = __import__('os')

print(os.path.abspath('.'))

帮助方法

在控制台执行help()进入帮助模式。可以随意输入变量或者变量的类型。输入q退出

或者直接执行help(o),o是参数,查看和变量o有关的操作。。。

和调用相关

callable(o),o是参数,看这个变量是不是可调用。

如果o是一个函数名,就会返回True

callable实例

def func():pass

print(callable(func))  #参数是函数名,可调用,返回True

print(callable(123))   #参数是数字,不可调用,返回False

查看参数所属类型的所有内置方法

dir() 默认查看全局空间内的属性,也接受一个参数,查看这个参数内的方法或变量

查看某变量/数据类型的内置方法

print(dir(list))  #查看列表的内置方法

print(dir(int))  #查看整数的内置方法

和数字相关

数字——数据类型相关:bool(布尔类型),int(数值类型),float(浮点型),complex(复数)

复数——complex

实数:有理数

无理数--不限不循环数,比如π

虚数:虚无缥缈的数 虚数以J为单位

flomat = 浮点数(有限循环小数、无限循环小数)!==小数 :无限不循环小数

数字——进制转换相关:bin(二进制),oct(八进制),hex(十六进制)

print(bin(3243)) #结果: 0b110010101011

print(oct(3243)) #结果: 0o6253

print(hex(3243)) #结果: 0xcab

数字——数学运算:abs(绝对值),divmod(除余),min(最小值),max(最大值),sum(求和),round(保留几位小数,四舍五入),pow(幂次方)

abs

print(-abs(434)) # -434

print(-abs(-434)) # -434

print(abs(434)) # 434

print(abs(-434)) # 434

divmodprint(divmod(9,2))

# 结果:(4, 1)

minprint(min(9,2,key=none)) key后面跟的是可调用对象

结果:2

maxprint(max(9,2,key=none))

# 结果:9

sum(可迭代的数据)print(sum([9,2,65]))

# 结果:76

roundprint(round(34.3434,2))

#结果:34.43

powprint(pow(3,3))

#结果:27

和数据结果相关

序列——列表和元组相关的:list和tuple

序列——字符串相关的:str,format,bytes,bytearry,memoryview,ord,chr,ascii,repr

内置函数format

说明:

1. 函数功能将一个数值进行格式化显示。

2. 如果参数format_spec未提供,则和调用str(value)效果相同,转换成字符串格式化。

print(format(32.35353), type(format(32.35353))) # 32.35353

print(str(32.35353), type(str(32.35353))) # 32.35353

3. 对于不同的类型,参数format_spec可提供的值都不一样

#字符串可以提供的参数,指定对齐方式,是右对齐,^是居中对齐

print(format('test', '<20'))

print(format('test', '>20'))

print(format('test', '^20'))

#整形数值可以提供的参数有 'b' 'c' 'd' 'o' 'x' 'X' 'n' None

>>> format(3,'b') #转换成二进制

'11'

>>> format(97,'c') #转换unicode成字符

'a'

>>> format(11,'d') #转换成10进制

'11'

>>> format(11,'o') #转换成8进制

'13'

>>> format(11,'x') #转换成16进制 小写字母表示

'b'

>>> format(11,'X') #转换成16进制 大写字母表示

'B'

>>> format(11,'n') #和d一样

'11'

>>> format(11) #默认和d一样

'11'

#浮点数可以提供的参数有 'e' 'E' 'f' 'F' 'g' 'G' 'n' '%' None

>>> format(314159267,'e') #科学计数法,默认保留6位小数

'3.141593e+08'

>>> format(314159267,'0.2e') #科学计数法,指定保留2位小数

'3.14e+08'

>>> format(314159267,'0.2E') #科学计数法,指定保留2位小数,采用大写E表示

'3.14E+08'

>>> format(314159267,'f') #小数点计数法,默认保留6位小数

'314159267.000000'

>>> format(3.14159267000,'f') #小数点计数法,默认保留6位小数

'3.141593'

>>> format(3.14159267000,'0.8f') #小数点计数法,指定保留8位小数

'3.14159267'

>>> format(3.14159267000,'0.10f') #小数点计数法,指定保留10位小数

'3.1415926700'

>>> format(3.14e+1000000,'F')  #小数点计数法,无穷大转换成大小字母

'INF'

#g的格式化比较特殊,假设p为格式中指定的保留小数位数,先尝试采用科学计数法格式化,得到幂指数exp,如果-4<=exp

>>> format(0.00003141566,'.1g') #p=1,exp=-5 ==》 -4<=exp

'3e-05'

>>> format(0.00003141566,'.2g') #p=1,exp=-5 ==》 -4<=exp

'3.1e-05'

>>> format(0.00003141566,'.3g') #p=1,exp=-5 ==》 -4<=exp

'3.14e-05'

>>> format(0.00003141566,'.3G') #p=1,exp=-5 ==》 -4<=exp

'3.14E-05'

>>> format(3.1415926777,'.1g') #p=1,exp=0 ==》 -4<=exp

'3'

>>> format(3.1415926777,'.2g') #p=1,exp=0 ==》 -4<=exp

'3.1'

>>> format(3.1415926777,'.3g') #p=1,exp=0 ==》 -4<=exp

'3.14'

>>> format(0.00003141566,'.1n') #和g相同

'3e-05'

>>> format(0.00003141566,'.3n') #和g相同

'3.14e-05'

>>> format(0.00003141566) #和g相同

'3.141566e-05'

bytearry

ret = bytearray('alex',encoding='utf-8')

print(ret) # bytearray(b'alex')

print(id(ret)) # 14402816

print(ret[0]) # 97

ret[0] = 65

print(ret) # bytearray(b'Alex')

print(id(ret)) # 14402816

memoryview

ret = memoryview(bytes('你好',encoding='utf-8'))

print(ret) #

print(len(ret)) # 6

print(bytes(ret[:3]).decode('utf-8')) #你

print(bytes(ret[3:]).decode('utf-8')) #好

序列:reversed,l = (1,2,23,213,5612,342,43)

print(l) #(1, 2, 23, 213, 5612, 342, 43)

print(reversed(l)) # 得到一个翻转生成器

print(list(reversed(l))) #使用List强制取数,数据是翻转过来的的

生成一个切片规则:slice

l = (1,2,23,213,5612,342,43)

sli = slice(1, 5, 2)

print(l[sli])

#(2,213)

数据集合——字典和集合:dict

dict={key:values}

set(集合)

认识集合

由一个或多个确定的元素所构成的整体叫做集合。

集合中的元素有三个特征:

1.确定性(集合中的元素必须是确定的)

2.互异性(集合中的元素互不相同。例如:集合A={1,a},则a不能等于1)

3.无序性(集合中的元素没有先后之分),如集合{3,4,5}和{3,5,4}算作同一个集合。

*集合概念存在的目的是将不同的值存放到一起,不同的集合间用来做关系运算,无需纠结于集合中某个值

集合的定义

st = {1,'ere',3,5}

#定义可变集合

set_test=set('hello')

print(set_test)

# {'e', 'l', 'o', 'h'}

#改为不可变集合frozenset

set_test=set('hello')

f_set_test=frozenset(set_test)

print(f_set_test)

#结果 frozenset({'e', 'l', 'h', 'o'})

集合的常用操作及关系运算

元素的增加

单个元素的增加 : add(),add的作用类似列表中的append

对序列的增加 : update(),而update类似extend方法,update方法可以支持同时传入多个参数

a={1,2}

a.update([1,2],[1,3,45]) # 增加的内容是可迭代的,类似extend方法

print(a)

# {1, 2, 3, 45}

a.update('hello')

print(a)

# {1, 2, 3, 'l', 45, 'h', 'o', 'e'}

a.add(69) # 只能添加一个参数,类似类表达append

print(a)

# {'h', 1, 2, 3, 'o', 69, 'e', 45, 'l'}

元素的删除

集合删除单个元素有两种方法:

元素不在原集合中时

set.discard(x)不会抛出异常

set.remove(x)会抛出KeyError错误

a = {'h', 1, 2, 3, 'o', 69, 'e', 45, 'l'}

a.discard(1)

print(a)

# {2, 3, 69, 'l', 'h', 45, 'o', 'e'}

a.remove('k') # 不存在改值是会报KeyError

print(a)

pop():由于集合是无序的,pop返回的结果不能确定,且当集合为空时调用pop会抛出KeyError错误,clear():清空集合

a = {'h', 1, 2, 3, 'o', 69, 'e', 45, 'l'}

# a.pop()

# print(a)

# {2, 3, 69, 'e', 45, 'o', 'l', 'h'}

a.pop()

print(a)

# {2, 3, 69, 'e', 'o', 45, 'h', 'l'}

a.clear()

print(a)

a.pop() # 当集合为空时会报错KeyError: 'pop from an empty set'

集合操作

union,|=:合集 两种写法union |

a = {1,2,3}

b = {2,3,4,5}

print(a.union(b))

print(a|b)

结果为:{1, 2, 3, 4, 5}

&.&=:交集 两种写法 intersection &

a = {1,2,3}

b = {2,3,4,5}

print(a.intersection(b))

print(a&b)

结果为:{2, 3}

-,-=:差集 两种写法 difference -a = {1,2,3}

b = {2,3,4,5}

print(a.difference(b))

print(a-b)

结果为:{1}

#^,^=:对称差集 两种写法symmetric_difference ^

a = {1,2,3}

b = {2,3,4,5}

print(a.symmetric_difference(b))

print(a^b)

# {1, 4, 5}

包含关系

in,not in:判断某元素是否在集合内

==,!=:判断两个集合是否相等

两个集合之间一般有三种关系,相交、包含、不相交。在Python中分别用下面的方法判断:

set.isdisjoint(s):判断两个集合是不是不相交

s = {1}

d = {2}

print(s.isdisjoint(d)) # True

s = {2}

d = {2}

print(s.isdisjoint(d)) # False

set.issuperset(s):判断集合是不是包含其他集合,等同于a>=b

s = {2,'fff','efefe'}

d = {2,'fff'}

print(s.issuperset(d)) # True 相当于s集合里面的元素是否已经包含了集合d里面的所以元素

set.issubset(s):判断集合是不是被其他集合包含,等同于a<=b

s = {2,'fff'}

d = {2,'fff','efefe'}

print(s.issubset(d)) # True 与上面反之相当于d集合里面的元素是否已经包含了集合s里面的所以元素

集合的工厂函数

classset(object):"""set() -> new empty set object

set(iterable) -> new set object

Build an unordered collection of unique elements."""

def add(self, *args, **kwargs): #real signature unknown

"""Add an element to a set.

This has no effect if the element is already present."""

pass

def clear(self, *args, **kwargs): #real signature unknown

"""Remove all elements from this set."""

pass

def copy(self, *args, **kwargs): #real signature unknown

"""Return a shallow copy of a set."""

pass

def difference(self, *args, **kwargs): #real signature unknown

"""相当于s1-s2

Return the difference of two or more sets as a new set.

(i.e. all elements that are in this set but not the others.)"""

pass

def difference_update(self, *args, **kwargs): #real signature unknown

"""Remove all elements of another set from this set."""

pass

def discard(self, *args, **kwargs): #real signature unknown

"""与remove功能相同,删除元素不存在时不会抛出异常

Remove an element from a set if it is a member.

If the element is not a member, do nothing."""

pass

def intersection(self, *args, **kwargs): #real signature unknown

"""相当于s1&s2

Return the intersection of two sets as a new set.

(i.e. all elements that are in both sets.)"""

pass

def intersection_update(self, *args, **kwargs): #real signature unknown

"""Update a set with the intersection of itself and another."""

pass

def isdisjoint(self, *args, **kwargs): #real signature unknown

"""Return True if two sets have a null intersection."""

pass

def issubset(self, *args, **kwargs): #real signature unknown

"""相当于s1<=s2

Report whether another set contains this set."""

pass

def issuperset(self, *args, **kwargs): #real signature unknown

"""相当于s1>=s2

Report whether this set contains another set."""

pass

def pop(self, *args, **kwargs): #real signature unknown

"""Remove and return an arbitrary set element.

Raises KeyError if the set is empty."""

pass

def remove(self, *args, **kwargs): #real signature unknown

"""Remove an element from a set; it must be a member.

If the element is not a member, raise a KeyError."""

pass

def symmetric_difference(self, *args, **kwargs): #real signature unknown

"""相当于s1^s2

Return the symmetric difference of two sets as a new set.

(i.e. all elements that are in exactly one of the sets.)"""

pass

def symmetric_difference_update(self, *args, **kwargs): #real signature unknown

"""Update a set with the symmetric difference of itself and another."""

pass

def union(self, *args, **kwargs): #real signature unknown

"""相当于s1|s2

Return the union of sets as a new set.

(i.e. all elements that are in either set.)"""

pass

def update(self, *args, **kwargs): #real signature unknown

"""Update a set with the union of itself and others."""

pass

def __and__(self, *args, **kwargs): #real signature unknown

"""Return self&value."""

pass

def __contains__(self, y): #real signature unknown; restored from __doc__

"""x.__contains__(y) <==> y in x."""

pass

def __eq__(self, *args, **kwargs): #real signature unknown

"""Return self==value."""

pass

def __getattribute__(self, *args, **kwargs): #real signature unknown

"""Return getattr(self, name)."""

pass

def __ge__(self, *args, **kwargs): #real signature unknown

"""Return self>=value."""

pass

def __gt__(self, *args, **kwargs): #real signature unknown

"""Return self>value."""

pass

def __iand__(self, *args, **kwargs): #real signature unknown

"""Return self&=value."""

pass

def __init__(self, seq=()): #known special case of set.__init__

"""set() -> new empty set object

set(iterable) -> new set object

Build an unordered collection of unique elements.

# (copied from class doc)"""

pass

def __ior__(self, *args, **kwargs): #real signature unknown

"""Return self|=value."""

pass

def __isub__(self, *args, **kwargs): #real signature unknown

"""Return self-=value."""

pass

def __iter__(self, *args, **kwargs): #real signature unknown

"""Implement iter(self)."""

pass

def __ixor__(self, *args, **kwargs): #real signature unknown

"""Return self^=value."""

pass

def __len__(self, *args, **kwargs): #real signature unknown

"""Return len(self)."""

pass

def __le__(self, *args, **kwargs): #real signature unknown

"""Return self<=value."""

pass

def __lt__(self, *args, **kwargs): #real signature unknown

"""Return self

pass@staticmethod#known case of __new__

def __new__(*args, **kwargs): #real signature unknown

"""Create and return a new object. See help(type) for accurate signature."""

pass

def __ne__(self, *args, **kwargs): #real signature unknown

"""Return self!=value."""

pass

def __or__(self, *args, **kwargs): #real signature unknown

"""Return self|value."""

pass

def __rand__(self, *args, **kwargs): #real signature unknown

"""Return value&self."""

pass

def __reduce__(self, *args, **kwargs): #real signature unknown

"""Return state information for pickling."""

pass

def __repr__(self, *args, **kwargs): #real signature unknown

"""Return repr(self)."""

pass

def __ror__(self, *args, **kwargs): #real signature unknown

"""Return value|self."""

pass

def __rsub__(self, *args, **kwargs): #real signature unknown

"""Return value-self."""

pass

def __rxor__(self, *args, **kwargs): #real signature unknown

"""Return value^self."""

pass

def __sizeof__(self): #real signature unknown; restored from __doc__

"""S.__sizeof__() -> size of S in memory, in bytes"""

pass

def __sub__(self, *args, **kwargs): #real signature unknown

"""Return self-value."""

pass

def __xor__(self, *args, **kwargs): #real signature unknown

"""Return self^value."""

pass

__hash__ = None

集合的工厂函数

数据集合:len,sorted,enumerate,all,any,zip,filter,map

len 长度

s = 'egef'

print(len(s)) # 4

sorted(参数,key=None,reverse=False) 排序,会生成一个新的值,原值的结果不会变,需要保留原值不变的情况下可以使用此函数

s = {1,4,3,26,4}

ret = sorted(s)print(ret) # [1, 3, 4, 4, 26]print(s) # [1, 4, 3, 26, 4]

对List、Dict进行排序,Python提供了两个方法

对给定的List L进行排序,

方法1.用List的成员函数sort进行排序,在本地进行排序,不返回副本

方法2.用built-in函数sorted进行排序(从2.4开始),返回副本,原始输入不变

--------------------------------sorted---------------------------------------

sorted(iterable, key=None, reverse=False)

Return a new list containing all items from the iterable in ascending order.

A custom key function can be supplied to customise the sort order, and the

reverse flag can be set to request the result in descending order.

------------------------------------------------------------------------------------------------------------------------

参数说明:

iterable:是可迭代类型;

key:传入一个函数名,函数的参数是可迭代类型中的每一项,根据函数的返回值大小排序;

reverse:排序规则. reverse = True  降序 或者 reverse = False 升序,有默认值。

返回值:有序列表

列表按照其中每一个值的绝对值排序

l1 = [1,3,5,-2,-4,-6]

l2 = sorted(l1,key=abs)

print(l1) # [1, 3, 5, -2, -4, -6]

print(l2) # [1, -2, 3, -4, 5, -6]

列表按照每一个元素的len排序

列表按照每个元素的长度进行排序

l = [[1,2],[3,4,5,6],(7,),'123']

print(sorted(l,key=len),)

# [(7,), [1, 2], '123', [3, 4, 5, 6]]

enumerate(参数) 枚举 生成可迭代对象里,前面生成一个序列号s = ['re','kgo','fons','fefe']for i in enumerate(s): #参数为可迭代对象print(i)(0, 're')(1, 'kgo')(2, 'fons')(3, 'fefe')

all(参数) # 参数为可迭代对象,检测对象中是否包含FALSE 如有一个返回Trues = ['kf','fjeof',' ']print(all(s)) # True

any(参数)检测参数中是否有True,如有一个为True就反之True

s = ['fe','fjei','']

print(any(s)) # True

zip(参数1,参数2,。。) 参数为可迭代对象,把各个参数分别拉起来组成一个个元组,注意是对称拉

s1 = {2,2,4,5}

s2 = ['ad','fef','ef']

ret = zip(s1,s2,'fe','fe') # 得到一个可迭代对象

print(list(ret))#列表里面包含元组

# [(2, 'ad', 'f', 'f'), (4, 'fef', 'e', 'e')]

for i in ret: # 这样得到的结果为元组print(i)

(2, 'ad', 'f', 'f')

(4, 'fef', 'e', 'e')

filter

filter()函数接收一个函数 f 和一个list,这个函数 f 的作用是对每个元素进行判断,返回 True或 False,filter()根据判断结果自动过滤掉不符合条件的元素,返回由符合条件元素组成的新list

例如,要从一个list [1, 4, 6, 7, 9, 12, 17]中删除偶数,保留奇数,首先,要编写一个判断奇数的函数:

lis = [1, 4, 6, 7, 9, 12, 17]

def is_odd(x):

return x % 2 == 1

ret = filter(is_odd,lis) # 得到一个可迭代的

print(list(ret)) # [1, 7, 9, 17] #根据判断自动返回符合条件值,新成一个新的列表利用filter()

可以完成很多有用的功能,例如,删除 None 或者空字符串:

lis = ['test', None, '', 'str', ' ', 'END']

def is_not_empty(s):

return s and len(s.strip()) > 0 # 返回True ,None转换为布尔值为FALSE

print(list(filter(is_not_empty,lis)))

注意: s.strip(rm) 删除 s 字符串中开头、结尾处的 rm 序列的字符。

当rm为空时,默认删除空白符(包括'\n', '\r', '\t','\f', ' '),如下:

a = '\t\t123\r\n\f'''

print(a.strip())

# 123

请利用filter()过滤出1~100中平方根是整数的数,即结果应该是:

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

方法:

import math

def is_sqr(x):

return math.sqrt(x) % 1 == 0

print(list(filter(is_sqr, range(1, 101))))

map

Python中的map函数应用于每一个可迭代的项,返回的是一个结果list。如果有其他的可迭代参数传进来,map函数则会把每一个参数都以相应的处理函数进行迭代处理。map()函数接收两个参数,一个是函数,一个是序列,map将传入的函数依次作用到序列的每个元素,并把结果作为新的list返回。返回的是一个可迭代对象

有一个list, L = [1,2,3,4,5,6,7,8],我们要将f(x)=x^2作用于这个list上,那么我们可以使用map函数处理

l = [1,2,3,4,5,6,7,8]

def pow2(x):

return pow(x,2)

ret = map(pow2, l) #如这里使用filter会原封不动把原值返回回来,不会进行计算

print(list(ret))

结果:[1, 4, 9, 16, 25, 36, 49, 64]

匿名函数

匿名函数:为了解决那些功能很简单的需求而设计的一句话函数

# 这段代码

def calc(n):

return n ** n #相对于 (10 * 10*10*10*10*10*10*10*10*10)

print(calc(10))

# 换成匿名函数

calc = lambda n: n ** n

print(calc(10))

上面是我们对calc这个匿名函数的分析,下面给出了一个关于匿名函数格式的说明

函数名 = lambda 参数 :返回值 -->注意只能书写一行代码

#参数可以有多个,用逗号隔开

#匿名函数不管逻辑多复杂,只能写一行,且逻辑执行结束后的内容就是返回值

#返回值和正常的函数一样可以是任意数据类型

我们可以看出,匿名函数并不是真的不能有名字。

匿名函数的调用和正常的调用也没有什么分别。 就是 函数名(参数) 就可以了~~~

练一练:

请把以下函数变成匿名函数

def add(x,y):

return x+y

add = lambda x,y:x+y 改变为匿名函数的写法

print(add(9,10)) #19

上面是匿名函数的函数用法。除此之外,匿名函数也不是浪得虚名,它真的可以匿名。在和其他功能函数合作的时候

l=[3,2,100,999,213,1111,31121,333]

print(max(l))

# 求出最大值

dic={'k1':10,'k2':100,'k3':30}

def func(key):

return dic[key]

print(max(dic,key=func)) # k2 这个要提前定义一个函数,key后面是传入字典中每个键,返回的是键对应的值,然后去最大值

print(max(dic,key=lambda k:dic[k])) # k2 匿名函数值需要些一行就可以了

print(dic[max(dic,key=lambda k:dic[k])]) # 100 去字典中最大的值

#lambda匿名函数写法

res = map(lambda x:x**2,[1,5,7,4,8])

for i in res:

print(i)

#正常函数写法

def res(x):

return pow(x,2)

ret = map(res,[1,5,7,4,8])

for i in ret:

print(i)

#匿名函数写法

res = filter(lambda x:x>10,[5,8,11,9,15])

for i in res:

print(i)

#正常函数写法

def res(x):

return x>10

ret = filter(res,[5,8,11,9,15])

for i in ret:

print(i)

面试题练一练

现有两个元组(('a'),('b')),(('c'),('d')),请使用python中匿名函数生成列表[{'a':'c'},{'b':'d'}]

1.匿名函数

#zip

ret = zip((('a'),('b')),(('c'),('d')))

# def func(tup): #一般函数写法

# return {tup[0]:tup[1]}

# print(list(map(func,ret)))

# 匿名函数写法

print(list(map(lambda tup:{tup[0]:tup[1]} ,ret)))

2.下面打印的值是什么

d = lambda p:p*2

t = lambda p:p*3

x = 2

x = d(x) # 4

x = t(x) # 12

x = d(x) # 24

print (x) # 24

最后结果为:24

3.以下代码的输出是什么?请给出答案并解释。

def func():

return [lambda x:i*x for i in range(4)]

print([m(2) for m in func()]) # 其实不太明白lambda表达式不带名字时的调用方法

# [6, 6, 6, 6]

# 请修改multipliers的定义来产生期望的结果。

def func():

return (lambda x:i*x for i in range(4))

print([m(2) for m in func()])

# [0, 2, 4, 6]

本章小结

说学习内置函数,不如说整理自己的知识体系。其实整理这些内置函数的过程也是在整理自己的知识体系。

我们讲课的时候会归类:常用或者不常用,主要还是根据场景而言。

一个优秀的程序员就应该是在该用这个方法的时候信手拈来,把每一个内置的函数都用的恰到好处。

要想做到这一点,至少要先了解,才能在需要的时候想起,进而将它用在该用的地方。

但是在这里,我还是以自己的一点经验之谈,把几个平时工作中相对更常用的方法推荐一下,请务必重点掌握:

其他:input,print,type,hash,open,import,dir

str类型代码执行:eval,exec

数字:bool,int,float,abs,divmod,min,max,sum,round,pow

序列——列表和元组相关的:list和tuple

序列——字符串相关的:str,bytes,repr

序列:reversed,slice

数据集合——字典和集合:dict,set,frozenset

数据集合:len,sorted,enumerate,zip,filter,map

一下带key的5个函数,一般跟匿名函数搭配使用

min max filter map sorted

strip 替换是一个个字符进行替换的,不是整体进行替换的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值