12、内置函数


12.1、map函数:

map函数处理的数据类型必须为可迭代对象

map处理序列中的每个元素,得到的结果是一个列表对象,该列表对象元素个数及位置与原来一样

1、map函数内部结构:

def map_test(func,array): #func=lambda x:x.upper() array="liuchang"

ret=[]

for i in array:

res=func(i)

ret.append(res)

return ret


msg='liuchang'

print(list(map_test(lambda x:x.upper(),msg)))


2、使用map函数:

(1)

msg='liuchang'

print(list(map(lambda x:x.upper(),msg)))


(2)

l=[1,2,3,4,5]

print((map(str,l)))

# <map object at 0x000001D4C6F364A8>

print(list(map(str,l)))


12.2、filter函数:

filter函数处理的数据类型必须为可迭代对象

filter遍历序列中的每个元素,判断每个元素得到布尔值,如果是True则留下来,最后得到一个列表对象

1、filter函数内部结构:

def filter_test(func, array):

ret = []

for p in array:

if func(p):

ret.append(p)

return ret


movie_people = ['1_sb', '2_sb', '3_', '4_sb']

res = filter_test(list(lambda n: not n.endswith('sb'), movie_people))

print(res)


2、使用filter函数:

(1)

movie_people = ['1_sb', '2_sb', '3_', '4_sb']

print(filter(lambda n: not n.endswith('sb'), movie_people))

# <filter object at 0x00000249D4B8F668>

print(list(filter(lambda n: not n.endswith('sb'), movie_people)))


(2)

people=[

{'name':'lc1','age':1000},

{'name':'lc2','age':10000},

{'name':'lc','age':9000},

{'name':'lc3','age':18},

]

print(list(filter(lambda p:p['age']<=18,people)))


12.3、reduce函数:

reduce函数处理的数据类型必须为可迭代对象

reduce处理一个序列,然后把序列进行合并操作,最终得到一个合并结果

注意:reduce函数只能处理相同数据类型的数据

1、reduce函数内部结构:

num_l=[1,2,3,100]

def reduce_test(func,array,init=None):

if init is None:

res=array.pop(0)

else:

res=init

for num in array:

res=func(res,num)

return res


print(reduce_test(lambda x,y:x*y,num_l,10))


2、使用reduce函数:

from functools import reduce

num_l=[1,2,3,100]

print(reduce(lambda x,y:x+y,num_l))

print(reduce(lambda x,y:x*y,num_l,10))

# reduce(函数, 可迭代对象, 可迭代对象初始值,如果不定义取的是可迭代对象的第一个值)


12.4、拷贝问题:

1、复杂数据类型赋值:

# 共享一块内存空间,清空一个另一个受影响:

a = [1, 3, 4]

b = a

b[0] = 8

print(a, b)

# [8, 3, 4] [8, 3, 4]


2、简单数据类型赋值:

# 不共享内存空间,清空一个另一个不受影响:

c = 1

d = c

d = 2

print(c, d)

# 1 2


3、浅拷贝:

# 浅拷贝第一层不共享内存空间,其它层共享内存空间,清空一个另一个不受影响:

e = [1, 2, [1, 2]]

f = e.copy()

e[0] = 88

e[2][0] = 99

print(e, f)

# [88, 2, [99, 2]] [1, 2, [99, 2]]


4、深拷贝:

# 深拷贝就是完全独立克隆一份:

import copy


g = [1, 2, [1, 2]]

h = copy.deepcopy(g)

g[2][1] = 88

print(g, h)

# [1, 2, [1, 88]] [1, 2, [1, 2]]


12.5、求绝对值:

print(abs(-1))

# 求数字的绝对值

# 1

print(abs(1))

# 1


12.6、迭代对象的且运算:

print(all((1,2,'1')))

# all() 函数用于判断给定的可迭代参数 iterable 中的所有元素是否都为 TRUE,如果是返回 True,否则返回 False。

# 元素除了是 0、空、None、False 外都算 True。注意:空字符串不是空;

# 类似于且运算

# True

print(all([1,2,'1','',0]))

# False

print(all(' '))

# True


12.7、迭代对象的或运算:

print(any([0,'']))

# any() 函数用于判断给定的可迭代参数 iterable 是否全部为 False,如果是返回 False,如果有一个为 True,则返回 True。

# 元素除了是 0、空、FALSE 外都算 TRUE。注意:空字符串不是空;

# 类似于或运算

# False

print(any([0,1,'']))

# True


12.8、将整数转化为2进制:

print(bin(3))

# bin() 返回一个整数 int 或者长整数 long int 的二进制表示。

# 0b11


12.9、bool值判断:

print(bool(''))

print(bool(None))

print(bool(0))

print(bool(False))

# 0、False、空、None的布尔值为False,其余都为True

# False

# False

# False

# False


12.10、bytes编码:

name='你好'

print(bytes(name,encoding='utf-8'))

print(bytes(name,encoding='utf-8').decode('utf-8'))

# b'xe4xbdxa0xe5xa5xbd'

# 你好


print(bytes(name,encoding='gbk'))

print(bytes(name,encoding='gbk').decode('gbk'))

# b'xc4xe3xbaxc3'

# 你好


# print(bytes(name,encoding='ascii'))

# ascii不能编码中文


12.11、char函数:

print(chr(75))

# chr() 用一个范围在 range(256)内的(就是0~255)整数作参数,返回一个对应的字符。

# K


print(chr(97))

# a

print(ord('a'))

# 97

print(round(3.5))

# 4


12.12、dict函数:

print(dir(dict))

# 查看函数的方法


12.13、divmod函数:

print(divmod(10,3))

# divmod() 函数把除数和余数运算结果结合起来,返回一个包含商和余数的元组(a / b, a % b)。

# (3, 1)


12.14、evall函数:

dic={'name':'lc'}

dic_str=str(dic)

print(dic_str)

print(type(dic_str))

# {'name': 'lc'}

# <class 'str'>


print(type(1))

# <class 'int'>

print(str('1'))

# 1

print(type(str({'a':1})))

# <class 'str'>

dic_str=str({'a':1})

print(type(eval(dic_str)))

# <class 'dict'>


12.15、hash函数:

# 可hash的数据类型即不可变数据类型,不可hash的数据类型即可变数据类型

name='lc'

print('--->before',hash(name))

name='chang'

print('=-=>after',hash(name))


12.16、help函数:

# 查看函数使用说明

print(help(all))


12.17、十进制整数数转化为二进制、16进制、8进制:

print(bin(10))

# 10进制->2进制

# 0b1010

print(hex(12))

# 10进制->16进制

# 0xc

print(oct(12))

# 10进制->8进制

# 0o14


12.18、验证摸个数据是某个数据类型:

print(isinstance(1,int))

print(isinstance('abc',str))

print(isinstance([],list))

print(isinstance({},dict))

print(isinstance({1,2},set))


# True

# True

# True

# True

# True


12.19、查看执行文件的全局变量和局部变量:

name='lc'

print(globals())

# {'__name__': '__main__', '__doc__': None, '__package__': None,

# '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x000001EF611F6278>,

# '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>,

# '__file__': 'D:/developer/PythonWorkSpace/python/test01.py', '__cached__': None, 'name': 'lc'}

print(__file__)

# D:/developer/PythonWorkSpace/python/test01.py


def test():

age='lc'

# print(globals())

print(locals())

test()

# {'age': 'lc'}


12.20、pow函数:

print(pow(3,3))

# 求次方

# 3**3

print(pow(3,3,2))

# 求次方的余数

# 3**3%2

# 1


12.21、reversed函数:

# reversed 函数返回一个反转的迭代器, 处理的数据类型必须是可迭代对象

l=[1,2,3,4]

print(list(reversed(l)))

# 将列表中的数据前后临时调转

# [4, 3, 2, 1]

print(l)

# [1, 2, 3, 4]


12.22、sum函数:

# 处理数字,处理的数据类型必须是可迭代对象

1、基本:

l=[1,2,3,4]

print(sum(l))

print(sum(range(5)))

# 10


12.23、max和min函数:

max、min 函数处理的是可迭代对象,相当于一个for循环去除每个元素进行比较,不同类型之间不能

进行比较;每个元素间进行比较,是从每个元素的第一个位置一次比较,如果这一个位置分出了大小,

后面都需要比较了,直接得出这两个元素的大小;

1、基本:

l=[1,3,100,-1,2]

print(min(l))

# -1

print(max(l))

# 100


2、列表比较:

(1)

age_dic={'lc_age':18,'lc1':20,'lc2':100,'lc3':30}

print(max(age_dic))

# 默认比较的是字典的key

# lc_age

print(max(age_dic.values()))

# 比较value,但不知道对应的key是什么

# 100


for item in zip(age_dic.values(),age_dic.keys()):

print(item)

# (18, 'lc_age')

# (20, 'lc1')

# (100, 'lc2')

# (30, 'lc3')


print(list(zip(age_dic.values(),age_dic.keys())))

# [(18, 'lc_age'), (20, 'lc1'), (100, 'lc2'), (30, 'lc3')]


print('=======>',list(max(zip(age_dic.values(),age_dic.keys()))))

# 结合zip使用

# =======> [100, 'lc2']

(2)

people=[

{'name':'lc1','age':1000},

{'name':'lc2','age':10000},

{'name':'lc3','age':9000},

{'name':'lc4','age':18},

]


ret=[]

for item in people:

ret.append(item['age'])

print(max(ret))

# 10000


print(max(people,key=lambda dic:dic['age']))

# {'name': 'lc2', 'age': 10000}


12.24、zip函数:

# zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,

# 然后返回由这些元组组成的列表。如果各个迭代器的元素个数不一致,则返回列表

# 长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。

# zip 方法在 Python 2 和 Python 3 中的不同:在 Python 3.x 中为了减少内存,

# zip() 返回的是一个对象。如需展示列表,需手动 list() 转换。


print(list(zip(['a','n','c'],(1,2,3))))

print(list(zip(('a','n','c'),(1,2,3,4))))

print(list(zip(('a','n','c','d'),(1,2,3))))

# [('a', 1), ('n', 2), ('c', 3)]

# [('a', 1), ('n', 2), ('c', 3)]

# [('a', 1), ('n', 2), ('c', 3)]


print(list(zip(('a','n','c','d','',''),(1,2,3,'','','d'))))

# [('a', 1), ('n', 2), ('c', 3), ('d', ''), ('', ''), ('', 'd')]


p={'name':'lc','age':18,'gender':'男'}

print(list(p.keys()))

# ['name', 'age', 'gender']

print(list(p.values()))

# ['lc', 18, '男']

print(list(zip(p.keys(),p.values())))

# [('name', 'lc'), ('age', 18), ('gender', '男')]


12.25、slice函数:

# 字符串的切片操作,处理的数据类型必须是可迭代对象

l='hellolc'

print(l[3:5])

print(l[slice(3,5)])

# lo

s2=slice(1,4,2)

print(l[s2])

# el

print(s2.start)

# 1

print(s2.stop)

# 4

print(s2.step)

# 2


12.26、sort函数:

# 注意:数据类型是可迭代对象,不同类型之间不可以比较大小

# sort排序默认从小大

1、基本:

l=[3,2,1,5,7]

print(sorted(l))

# [1, 2, 3, 5, 7]


2、列表比较:

(1)

people={

'lc': 11900,

'lc1':1200,

'lc2':300,

}

print(sorted(people))

# 默认按照key从小到大进行排序

# ['lc', 'lc1', 'lc2']

print(sorted(people,key=lambda key:people[key]))

# ['lc2', 'lc1', 'lc']

print(sorted(zip(people.values(),people.keys())))

# [(300, 'lc2'), (1200, 'lc1'), (11900, 'lc')]


(2)

people=[

{'name':'lc1','age':1000},

{'name':'lc2','age':10000},

{'name':'lc3','age':9000},

{'name':'lc4','age':18},

]

print(sorted(people,key=lambda dic:dic['age']))

# [{'name': 'lc4', 'age': 18}, {'name': 'lc1', 'age': 1000}, {'name': 'lc3', 'age': 9000}, {'name': 'lc2', 'age': 10000}]


12.27、数据交换:

a=1

b=2

print(a,b)

# 1 2

a,b=b,a

print(a,b)

# 2 1



原文地址:https://www.cnblogs.com/LiuChang-blog/p/12317202.html