Python基础(10)_内置函数、匿名函数、递归

一、内置函数

1、数学运算类

abs:求数值的绝对值

divmod:返回两个数值的商和余数,可用于计算页面数

>>> divmod(5,2)
(2, 1)

max:返回可迭代对象中的元素中的最大值或者所有参数的最大值

语法:max(iterable,key,default)

1 salaries={
2     'egon':3000,
3     'alex':100000000,
4     'wupeiqi':10000,
5     'yuanhao':2000
6 }
7 
8 print(max(salaries,key=lambda x:salaries[x]))
>>> max(1,2,3) # 传入3个参数 取3个中较大者
3
>>> max('1234') # 传入1个可迭代对象,取其最大元素值
'4'
>>> max(-1,0) # 数值默认去数值较大者
0
>>> max(-1,0,key = abs) # 传入了求绝对值函数,则参数都会进行求绝对值后再取较大者
-1

min:返回可迭代对象中的元素中的最小值或者所有参数的最小值

>>> min(1,2,3) # 传入3个参数 取3个中较小者
1
>>> min('1234') # 传入1个可迭代对象,取其最小元素值
'1'
>>> min(-1,-2) # 数值默认去数值较小者
-2
>>> min(-1,-2,key = abs)  # 传入了求绝对值函数,则参数都会进行求绝对值后再取较小者
-1

pow:返回两个数值的幂运算值或其与指定整数的模值

>>> pow(2,3)    #相当于2**3
>>> pow(2,3,5)  #相当于 pow(2,3)%5    

round:对浮点数进行四舍五入求值

>>> round(1.1314926,1)
1.1
>>> round(1.1314926,5)
1.13149

sum:对元素类型是数值的可迭代对象中的每个元素求和 

# 传入可迭代对象
>>> sum((1,2,3,4))
10
# 元素类型必须是数值型
>>> sum((1.5,2.5,3.5,4.5))
12.0
>>> sum((1,2,3,4),-10)
0

2、类型转换类

bool:根据传入的参数的逻辑值创建一个新的布尔值 

>>> bool() #未传入参数
False
>>> bool(0) #数值0、空序列等值为False
False
>>> bool(1)
True

int:根据传入的参数创建一个新的整数

float:根据传入的参数创建一个新的浮点数

complex:根据传入参数创建一个新的复数

>>> complex() #当两个参数都不提供时,返回复数 0j。
0j
>>> complex('1+2j') #传入字符串创建复数
(1+2j)
>>> complex(1,2) #传入数值创建复数
(1+2j)

str:返回一个对象的字符串表现形式(给用户)

bytearray:根据传入的参数创建一个新的字节数组

>>> bytearray('中文','utf-8')
bytearray(b'xe4xb8xadxe6x96x87')

  bytes:根据传入的参数创建一个新的不可变字节数组

>>> bytes('中文','utf-8')
b'xe4xb8xadxe6x96x87'

  ord:返回Unicode字符对应的整数

>>> ord('a')
97

  chr:返回整数所对应的Unicode字符

>>> chr(97) #参数类型为整数
'a'

  bin:将整数转换成2进制字符串

>>> bin(3) 
'0b11'

  oct:将整数转化成8进制数字符串

>>> oct(10)
'0o12'

  hex:将整数转换成16进制字符串

>>> hex(15)
'0xf'

  tuple:根据传入的参数创建一个新的元组

>>> tuple() #不传入参数,创建空元组
()
>>> tuple('121') #传入可迭代对象。使用其元素创建新的元组
('1', '2', '1')

  list:根据传入的参数创建一个新的列表

>>>list() # 不传入参数,创建空列表
[] 
>>> list('abcd') # 传入可迭代对象,使用其元素创建新的列表
['a', 'b', 'c', 'd']

  dict:根据传入的参数创建一个新的字典

>>> dict() # 不传入任何参数时,返回空字典。
{}
>>> dict(a = 1,b = 2) #  可以传入键值对创建字典。
{'b': 2, 'a': 1}
>>> dict(zip(['a','b'],[1,2])) # 可以传入映射函数创建字典。
{'b': 2, 'a': 1}
>>> dict((('a',1),('b',2))) # 可以传入可迭代对象创建字典。
{'b': 2, 'a': 1}

set:根据传入的参数创建一个新的集合

>>>set() # 不传入参数,创建空集合
set()
>>> a = set(range(10)) # 传入可迭代对象,创建集合
>>> a
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

frozenset:根据传入的参数创建一个新的不可变集合 

>>> a = frozenset(range(10))
>>> a
frozenset({0, 1, 2, 3, 4, 5, 6, 7, 8, 9})

enumerate:根据可迭代对象创建枚举对象  

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1)) #指定起始值
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

  range:根据传入的参数创建一个新的range对象

>>> a = range(10)
>>> b = range(1,10)
>>> c = range(1,10,3)
>>> a,b,c # 分别输出a,b,c
(range(0, 10), range(1, 10), range(1, 10, 3))
>>> list(a),list(b),list(c) # 分别输出a,b,c的元素
([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 4, 7])

  iter:根据传入的参数创建一个新的可迭代对象

>>> a = iter('abcd') #字符串序列
>>> a
<str_iterator object at 0x03FB4FB0>
>>> next(a)
'a'

slice:根据传入的参数创建一个新的切片对象

>>> c1 = slice(5) # 定义c1
>>> c1
slice(None, 5, None)
>>> c2 = slice(2,5) # 定义c2
>>> c2
slice(2, 5, None)
>>> c3 = slice(1,10,3) # 定义c3
>>> c3
slice(1, 10, 3)

  super:根据传入的参数创建一个新的子类和父类关系的代理对象

3、序列操作类

all:判断可迭代对象的每个元素是否都为True值

>>> all([1,2]) #列表中每个元素逻辑值均为True,返回True
True
>>> all([0,1,2]) #列表中0的逻辑值为False,返回False
False
>>> all(()) #空元组
True
>>> all({}) #空字典
True

  any:判断可迭代对象的元素是否有为True值的元素

>>> any([0,1,2]) #列表元素有一个为True,则返回True
True
>>> any([0,0]) #列表元素全部为False,则返回False
False
>>> any([]) #空列表
False
>>> any({}) #空字典
False

  filter:使用指定方法过滤可迭代对象的元素

>>> a = list(range(1,10)) #定义序列
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> def if_odd(x): #定义奇数判断函数
    return x%2==1

>>> list(filter(if_odd,a)) #筛选序列中的奇数
[1, 3, 5, 7, 9]

map:使用指定方法去作用传入的每个可迭代对象的元素,生成新的可迭代对象

>>> a = map(ord,'abcd')
>>> a
<map object at 0x03994E50>
>>> list(a)
[97, 98, 99, 100]

# map:映射
  l=[1,2,3,4]
  m=map(lambda x:x**2,l)
 print(list(m))

  names=['alex','wupeiqi','yuanhao']
  print(list(map(lambda item:item+'_SB',names)))  

next:返回可迭代对象中的下一个元素值

>>> a = iter('abcd')
>>> next(a)
'a'
#传入default参数后,如果可迭代对象还有元素没有返回,则依次返回其元素值,如果所有元素已经返回,则返回default指定的默认值而不抛出StopIteration 异常
>>> next(a,'e')
'e'

reversed:反转序列生成新的可迭代对象 

>>> a = reversed(range(10)) # 传入range对象
>>> a # 类型变成迭代器
<range_iterator object at 0x035634E8>
>>> list(a)
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

sorted:对可迭代对象进行排序,返回一个新的列表

 

>>> a = ['a','b','d','c','B','A']
>>> a
['a', 'b', 'd', 'c', 'B', 'A']

>>> sorted(a) # 默认按字符ascii码排序
['A', 'B', 'a', 'b', 'c', 'd']

>>> sorted(a,key = str.lower) # 转换成小写后再排序,'a'和'A'值一样,'b'和'B'值一样
['a', 'A', 'b', 'B', 'c', 'd']

l=[1,2,4,9,-1]
print(sorted(l)) #从小到大
print(sorted(l,reverse=True)) #从大到小

zip:聚合传入的每个迭代器中相同位置的元素,返回一个新的元组类型迭代器 

>>> x = [1,2,3] #长度3
>>> y = [4,5,6,7,8] #长度5
>>> list(zip(x,y)) # 取最小长度3
[(1, 4), (2, 5), (3, 6)]  

reduce:合并

from functools import reduce

print(redu ce(lambda x,y:x+y,range(100),100))

  filter:过滤

names=['alex_sb','yuanhao_sb','wupeiqi_sb','egon']
print(list(filter(lambda name:name.endswith('_sb'),names)))

  

4、对象操作类

id:返回对象的唯一标识符

>>> a = 'some text'
>>> id(a)
69228568

hash:获取对象的哈希值  

>>> hash('good good study')
1032709256

type:返回对象的类型,或者根据传入的参数创建一个新的类型  

>>> type(1) # 返回对象的类型
<class 'int'>

len:返回对象的长度  

二、匿名函数

匿名函数就是不需要显式的指定函数

#这段代码
def calc(n):
    return n**n
print(calc(10))
 
#换成匿名函数
calc = lambda n:n**n
print(calc(10))

匿名函数应用:

l=[3,2,100,999,213,1111,31121,333]
print(max(l))

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

print(max(dic))
print(dic[max(dic,key=lambda k:dic[k])])

  

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

输出
1
25
49
16
64

 

salaries={
	'egon':3000,
	'alex':100000000,
	'wupeiqi':10000,
	'yuanhao':2000
}

print(max(salaries,key=lambda x:salaries[x]))

三、递归

递归调用:
在调用一个函数的过程中,直接或者间接调用了该函数本身

#递归去列表的值
l=[1,[2,3,[4,5,[6,7,[8,9,[10,11,[12,13]]]]]]]
def func(l):
    for i in l:
        if isinstance(i,list):
            func(i)
        else:
            print(i)

func(l)

  

注:内置函数来自:http://blog.csdn.net/oaa608868/article/details/53506188

原文地址:https://www.cnblogs.com/hedeyong/p/7055696.html