函数之内置函数、匿名函数

一、内置函数

Python内置函数 

共68个

常用内置函数方法:

1、print

print('666',end='')
print('666')
print(1,2,3,4,5,sep='|')

666666
1|2|3|4|5
View Code

2、dir--查找对象的所有方法

print(dir(str))

['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
View Code

3、locals() 将局部的变量储存起来

globals() 将全局的变量,函数名,等等 储存起来

def func():
    name = 'alex'
    print(locals())
    print(globals())
func()
View Code

4、help()----将你查询的对象所有信息都拿出来

help(list)--可以吧列表的所有用法信息都输出出来

5、abs()----取绝对值

print(abs(-1))
print(abs(1))
def func(ret):
    print(44)
最大值
ret = max(1,2,-3,key=abs)
print(ret)------   -3
#最小值
ret = min([1,2,3])
print(ret)------   1
#sum iterable,初始值
ret = sum([1,2,3],10)
print(ret)------   16
View Code

6、callable---- 判断此变量是不是函数名

ex'
print(callable(name))----Flase
def func():
    print(666)
print(callable(func))-----Ture
View Code

7、hash()-----通过哈希表的规则,将对象转换成哈希值

sdsafsda'))
print(hash('fdsdsafsda'))
print(hash('dsakhdsafsda'))
print(hash(('a','b')))
print(hash((1,2,3,4)))
print(hash(True))

296489663101503432
8617324162733013048
4412082193174092575
1676122611624852323
7917385612527620386
485696759010151909
1
View Code

8 、all()----可迭代对象里面的所有的值转化成bool值如果都是True则,返回True

print(all([1,2,3,0]))
False
View Code

9、十进制与二进制十六进制转化

十进制转化成二进制
print(bin(100))--------------0b1100100
#将十进制转化成八进制
print(oct(9))-----------------0o11
#将十进制转化成十六进制
print(hex(33))--------------0x21
View Code

10、float()----数据类型中浮点

有限小数,无线循环小数,不包含(无线不循环小数)

print(1.35432,type(1.35432))
print(float(3))

1.35432 <class 'float'>
3.0
View Code

11、enumerate (iterable,start 起始值)   枚举

l = ['手机','电话','充气娃娃',]
for i in enumerate(l,1):
    print(i)

(1, '手机')
(2, '电话')
(3, '充气娃娃')

l = ['手机','电话','充气娃娃',]
for k,v in enumerate(l,1):
    print(k,v)

1 手机
2 电话
3 充气娃娃
View Code

12、eval() 有返回值 除去字符串两边的引号,返回里面的内容

13、exec() 没有返回值 除去字符串两边的引号,执行里面的代码

两者区别:

s = "{'name':'alex'}"
s1 = "1+2+3+4"

print(eval(s),type(eval(s)))
print(exec(s),type(exec(s)))
print(eval(s1),type(eval(s1)))

# {'name': 'alex'} <class 'dict'>
# None <class 'NoneType'>
# 10 <class 'int'>
View Code
code = '''for i in range(10):
    print(i)'''
print(exec(code))

0
1
2
3
4
5
6
7
8
9
None
View Code

 14、ord() 输入字符返回Unicode对应的编码位置

print(ord('a'))
print(ord('b'))
print(ord(''))

97
98
20013
View Code

15、chr()输入编码位置返回Unicode对应的字符

print(chr(97))
print(chr(20013))

a
中
View Code

16、ASCII()

print(ascii('a'))
print(ascii(''))  # \u

'a'
'\u56fd'
View Code

17、%r    repr 原形毕露

name = 'alex%r'%('sb')
print(name)
print(repr('[1,2]'))

alex'sb'
'[1,2]'
View Code

18、slice() 切片

l1 = [11,22,33,44]
print(l1[1::2])

【22,44】

sl = slice(1,4,2)
print(l1[sl])

【22,44】
等同
View Code

19、reversed()  (翻转) 形成一个行的迭代器

l1 = [11,33,22,44,'alex']

l2 = reversed(l1)
for i in l2:
    print(i)

alex
44
22
33
11
View Code

20、max()里面可以加函数,以函数规则返回最大值

dic = {'k1':20,'k2':30,'k3':100}
def func(x):
    return dic[x]
l1 = max(dic,key=func,)
print(l1)  #k3


dic = {3:20,2:30,1:100}
def func(x):
    return x
l1 = max(dic,key=func,)
print(l1)  #3
View Code

 

重要的内置函数

20、zip()  拉链方法------可以放置多个可迭代对象,以最少的可迭代对象的个数为基准,返回一个迭代器

l1 = [1,2,3,4,5]
l2 = ['wusir','alex','taibai']
l3 = ['*',"**"]
print(zip(l1,l2))
print(isinstance(zip(l1,l2),Iterator))
for i in zip(l1,l2,l3):
    print(i)

<zip object at 0x00000000028AC648>
True
(1, 'wusir', '*')
(2, 'alex', '**')
View Code

21、map()---可迭代对象

-------相当于推导式循环模式---[i*i for i in range(5)]

print(map(abs,[1,2,3,-4,-5,-7]))
for i in map(abs,[1,2,3,-4,-5,-7]):
    print(i)

<map object at 0x00000000021472B0>
1
2
3
4
5
7
View Code
def func(x):return x*x
for i in map(func,range(5)):
    print(i)


0
1
4
9
16
View Code

22、filter() (过滤、筛选)----可迭代对象

-------相当于推导式的筛选模式---[i for i in [1,2,3,4,5] if i % 2 == 0]

def func1(x):return x % 2 == 0
for i in filter(func1,[1,2,3,4,5]):
    print(i)

2
4
View Code

23、sord()(排序)---返回的是一个新列表

l1 = [1,4,3,5,7,8]
print(sorted(l1,))
print(l1)

[1, 3, 4, 5, 7, 8]
[1, 4, 3, 5, 7, 8]

  括号内可加函数,按照函数的规则排序

l = ['fsdafsa','fddsaf','qqq','fgasjdlg;dsjfg']
def func1(x):
  return len(x)
for i in sorted(l,key=func1):
    print(i)
print(sorted(l,key=len))

#
qqq
fddsaf
fsdafsa
fgasjdlg;dsjfg
['qqq', 'fddsaf', 'fsdafsa', 'fgasjdlg;dsjfg']
View Code

总结:

都是带key的 : zip max min map filter 返回的是迭代器  sorted 返回的是列表,一般与匿名函数lambda搭配使用

24、bytes()

s = '中国'.encode('utf-8')   #编码
print(s)

# s.decode('utf-8')     #解码
# s gbk的bytes  ---> utf-8的bytes
s = b'\xd6\xd0\xb9\xfa'
s1 = s.decode('gbk').encode('utf-8')
print(s1)

b'\xe4\xb8\xad\xe5\x9b\xbd'
View Code
# s = '中国'.encode('utf-8') #编码
# s = '中国'
# s= bytes(s,encoding='utf-8').decode('utf-8')
# print(s)
View Code

二、匿名函数

lambda

func = lambda x:x

func1 = lambda x,y:x+y

  应用:

def func(x):return x*x
for i in map(lambda x:x*x,[0,1,2,3,4]):
    print(i)
0
1
4
9
16
l1 = ['234','12','fsdafa','fdsagag']
for i in filter(lambda x:len(x) >= 3,l1):
    print(i)

234
fsdafa
fdsagag

例题1、

d = lambda x:x*2
t = lambda x:x*3
x = 2
x = d(x)
x = t(x)
x = d(x)
print(x)

x --24

例题2、

现在有两元祖(('a'),('b')),(('c'),('d')),请使用python 中的匿名函数生成列
表[{'a':'c'},{'b':'d'}]
tu1 = (('a'),('b'))
tu2 = (('c'),('d'))
func = lambda x,y:[{x[0]:y[0]},{x[1]:y[1]}]
print(func(tu1,tu2))

# [{'a': 'c'}, {'b': 'd'}]

注:

tu1 = (('a'),('b'))
tu2 = (2)
print(tu2)--------2
print(tu1)--------(‘a’,‘b’)

匿名函数后可以跟  三元运算

func()=  lambda x,y: x   if  x > 3  else  y

 

posted @ 2018-02-07 16:53  GuoXY  阅读(183)  评论(0编辑  收藏  举报