math模塊
在使用前導(dǎo)入math模塊 import math
常用方法
math.pow()方法
math.pow(x,y) 返回x的y次方
>>> math.pow(5.2)
25
math.sqrt()方法
math.sqrt(x) 返回x的平方根
>>> math.sqrt(25)
5
>>> math.sqrt(64)
8
math,factorial()方法
math.factorial(x) 返回x的階乘
什么是階乘 5! 54321=120
>>> math.factorial(6)
720
>>> math.factorial(5)
120
高級(jí)內(nèi)置函數(shù)即方法(常用)
1--map()函數(shù)
1--實(shí)例解釋
map()會(huì)根據(jù)提供的函數(shù)對(duì)指定的序列做映射
語(yǔ)法: map(function,iterable) # functuon函數(shù),iterable可迭代的序列(一個(gè)或者是多個(gè))
返回值;在python3中返回一個(gè)迭代器
實(shí)例1 # 一般的用法
def func(x):
return x**2
print(list(map(func,range(1,10)))) # 輸出[1,4,9,16,25,36,49,64,81]
# 由于map()返回值是一個(gè)迭代器,所以要list()輸出
# range(1,10)是一個(gè)可迭代對(duì)象,符合語(yǔ)法的注釋?zhuān)且粋€(gè)函數(shù)的引用
# 通過(guò)這樣,可以使用匿名函數(shù),通過(guò)匿名函數(shù)代替func函數(shù)
print(list(map(lambda x: x**2, range(1,10))))
實(shí)例2 # 可以把列的數(shù)字變成字符串和浮點(diǎn)
print(list(map(int, ['1','2','4']))) # 輸出[1,2,4]
print(list(map(str, range(1,5)))) # 輸出['1','2','3','4']
實(shí)例3 # 當(dāng)map()里面有多個(gè)參數(shù)時(shí)
a=[1,2,3] b=[4,5,6] c=[7,8,9]
print(list(map(lambda x: x+10, a))) # 輸出 [11,12,13]
print(list(map(lambda x,y: x*10+y, a, b))) # 輸出[14,25,36]
# 對(duì)上的兩個(gè)列表的元素進(jìn)行從新組合x(chóng)代表列表a中的元素,y代表列表b的元素,對(duì)a,b的元素進(jìn)行x*10+y
print(list(map(lambda x,y: y-x, a,b))) # 對(duì)a,b的元素進(jìn)行相減
# 輸出 [3,3,3]
....以此類(lèi)推有三個(gè)元素的時(shí)候
實(shí)例4 # 構(gòu)造字典
a='qwert'
b=range(1,6)
print(dict(map(lambda x,y:(x,y), a, b)))
# 輸出{'q':1, 'w':2, 'e':3, 'r':4, 't':5}
2--reduce()函數(shù)
2--實(shí)例解釋
reduce() 函數(shù)會(huì)對(duì)參數(shù)序列中元素進(jìn)行累積。
函數(shù)將一個(gè)數(shù)據(jù)集合(鏈表,元組等)中的所有數(shù)據(jù)進(jìn)行下列操作:
用傳給 reduce 中的函數(shù) function(有兩個(gè)參數(shù))先對(duì)集合中的第 1、2 個(gè)元素進(jìn)行操作,
得到的結(jié)果再與第三個(gè)數(shù)據(jù)用 function 函數(shù)運(yùn)算,最后得到一個(gè)結(jié)果。
reduce() 函數(shù)語(yǔ)法:
reduce(function, iterable[, initializer])
function -- 函數(shù),有兩個(gè)參數(shù)
iterable -- 可迭代對(duì)象
initializer -- 可選,初始參數(shù)
返回值 ----計(jì)算結(jié)果
# python3需要導(dǎo)入 from functools import reduce
實(shí)例1 # 基本操作
def add(x,y):
return x+y
print(reduce(add,[1,2,3,4,5]))
# 計(jì)算原理 (((1+2)+3)+4)+5
可以和匿名函數(shù)lambda一起使用
print(reduce(lambda(x,y:x+y,[1,2,3,4,5])))
# 可選參數(shù)
print(reduce(lambda(x,y:x+y,[1,2,3,4,5], 10))) # 結(jié)果是計(jì)算完結(jié)果之后+10
print(reduce(lambda(x,y:x*y,[1,2,3], 5))) # 結(jié)果是計(jì)算完結(jié)果之后*5
實(shí)例2
把[1,2,3,4,5] 轉(zhuǎn)換成12345
print(reduce(lambda x,y:x*10+y,[1,2,3,4,5]))
計(jì)算原理:(((1*10+2)*10+3)*10+4)*10+5
回顧map()函數(shù) 可以用map函數(shù)完成12345的轉(zhuǎn)換
print(''.join(list(map(str,[1,2,3,4,5]))))
3--filter()函數(shù) (俗稱(chēng)過(guò)濾器)
3--實(shí)例解釋
filter()函數(shù)用于過(guò)濾序列,過(guò)濾到不符合條件的元素,
返回有符合元素的組成的新列表
該接受兩個(gè)元素,第一個(gè)為函數(shù),第二個(gè)為序列,序列的
每個(gè)元素作為參數(shù)傳遞給進(jìn)行判斷,然后返回Ture或者是False,
最后將返回True的元素放到新的列表中
語(yǔ)法
filter(function, iterable)
function 判斷函數(shù)
iterable 可迭代對(duì)象
返回值為一個(gè) 迭代器對(duì)象
實(shí)例1 # 基本使用
def fun(x):
x % 2 == 0
print(list(filter(fun,range(1,10))))
和匿名函數(shù)一樣使用
print(list(filter(lambda x:x%2=0, range(1,10))))
在實(shí)際的運(yùn)算中,map和filter,reduce一起組合使用會(huì)非常頻繁,在面試的時(shí)候經(jīng)常要求一行代碼解決(硬性要求)
簡(jiǎn)單的例子
@ [1,2,3,4,5]每個(gè)元素平方后,求大于9的元素的和
1 求平方后的元素 new1_list = list(map(lambda x:x**2,[1,2,3,4,5])) # 輸出[1,4,9,16,25]
2 求大于9的元素 new2_list = list(filter(lambda x:x>9, new1_list)) # 輸出[16,25]
3 求和 reduce(lambdax, y: x+y, mew2_list) #輸出41
一行代碼print(reduce(lambda x, y: x+y,filter(lambda x: x>9,map(lambda x:x**2,[1,2,3,4,5]))))
print(sum(filter(lambda x: x>9, map(lambda x: x**2,[1,2,3,4,5])))) # 同樣可以達(dá)成效果
在使用的記住函數(shù)嵌套的順序,每個(gè)函數(shù)的語(yǔ)法
4--zip()函數(shù)
4--實(shí)例解釋
zip()函數(shù)用于可迭代對(duì)象為參數(shù),將參數(shù)中對(duì)應(yīng)的元素打包成一個(gè)元組,
然后返回這些元組組成的列表。
如果各個(gè)迭代器的元素不一樣,則返回列表的長(zhǎng)度與最短對(duì)象相同,利用*號(hào)操作符
可以將元組解壓成列表。
語(yǔ)法
zip(iter...)
iterable 一個(gè)或多個(gè)可迭代對(duì)象
返回值是個(gè)列表
實(shí)例 # 基本操作
a = [1, 2, 3]
b = [4, 5, 6]
c = [4, 5, 6, 7, 8]
print(zip(a, b)) # 輸出結(jié)果<zip object at 0x00000000028FF948>
print(list(zip(a, b))) # 記住返回值是個(gè)列表 執(zhí)行結(jié)果[(1, 4), (2, 5), (3, 6)]
print(list(zip(a, c))) # 執(zhí)行結(jié)果[(1, 4), (2, 5), (3, 6)] 以短的列表為主
print(dict(list(zip(a, b))))
# 如果是輸出字典,就不用list,直接
print(dict(zip(a, b))) #輸出{1: 4, 2: 5, 3: 6}
5--sorted()函數(shù)和當(dāng)中的key
5--實(shí)例解釋
sorted()函數(shù)對(duì) (所有的可迭代對(duì)象) 進(jìn)行排序操作
sort與sorted的區(qū)別:
1) sort是應(yīng)用在列表上的方法,sorted可對(duì)所有的迭代對(duì)象進(jìn)行操作.
2) list的sort方法返回的是對(duì)已經(jīng)存在的列表進(jìn)行操作,而內(nèi)建函數(shù)sorted方法返回的是一個(gè)新列表。
語(yǔ)法
sorted(iterable[,cmp[,key[,reverse]]])
iterable 可迭代對(duì)象
cmp 比較的函數(shù),具有兩個(gè)參數(shù),參數(shù)的值都是從可迭代對(duì)象取出,此函數(shù)必須遵守的規(guī)則是:
大于則返回1,小于則返回-1,等于則返回0
key 主要是用來(lái)比較元素,只有一個(gè)參數(shù),具體的函數(shù)的參數(shù)就是取自可迭代對(duì)象,指定可迭代對(duì)象的一個(gè)元素進(jìn)行排序
reverse 排序規(guī)則, reverse=True為降序,reverse=False為升序
返回值
返回一個(gè)新列表
revese()和revesed()是把列表倒序
【revese()方法和reversed()函數(shù)基本和sort(),sorted()一樣的】
sort()和sorted()是把列表按照大小的順序排序
實(shí)例 # 基本操作
a = [4,6,3,1,9]
b = a.sort()
print(b) # 沒(méi)有輸出
print(a) #輸出[1,3,4,6,9] sort()對(duì)已經(jīng)存在的列表操作,改變列表
c = sorted(a)
print(c) #輸出[1,3,4,6,9] sorted對(duì)存在的列表操作,返回一個(gè)新列表,原列表不變
重點(diǎn)對(duì)key的掌握
students = [('john', 'A', 15), ('jane', 'B', 12), ('dave','B', 10)]
print(sorted(students, key=lambda x: x[2]))
解釋 對(duì)學(xué)生列表的數(shù)字大小排序,在此用到key, key=lambda x: x[2]中的x通俗點(diǎn)就是列表中的每個(gè)元素,x[2]對(duì)元素進(jìn)行切片,得到數(shù)字,然后sorted根據(jù)數(shù)字大小進(jìn)行排序
復(fù)雜的問(wèn)題
nums_string = "2000 10003 1234000 44444444 9999 11 22 123" 對(duì)字符串的先切片得到每個(gè)數(shù)字的字符串,求和,根據(jù)大小重新排序
1 先對(duì)字符串進(jìn)行切片 new_list = nums_string.split(" ") #['2000','1003','1234000','44444444'...]
2 對(duì)得到的新列表中的數(shù)字字符串進(jìn)行相加得到結(jié)果 sum(int(n) for n in new_list)
此時(shí)用到key
print(' '.join(sorted(nums_string.split(' '), key=lambda x, sum(int(n) for n in x))))
6--enumerate()函數(shù)
6--實(shí)例解釋
enumerate()函數(shù)用于將一個(gè)可遍歷的數(shù)據(jù)對(duì)象(如列表,元組,或者是字符串)
組合成一個(gè)索引的序列,同時(shí)列出數(shù)據(jù)和數(shù)據(jù)的下標(biāo),一般用在For循環(huán)中
for index, item in enumerate(sequence):
print(index, item)
語(yǔ)法
enumerate(sequence, [start=0])
sequence 一個(gè)序列,迭代器或者是其他支持迭代的對(duì)象
start 下標(biāo)開(kāi)始的位置
返回值
返回enumerate()對(duì)象
實(shí)例 # 基本操作
a=['as','qw','df','ht','re']
for (j,k) in enumerate(a):
print(j,k) # j代表的索引,k代表元素
# 輸出 0 as 1 qw 2 df 3 ht 4 re
一個(gè)好玩的操作
for (j,k) in enumerate(a,3):
print(j,k) # 3表示索引起始位置
# 輸出 3 as 4 qw 5 df 6 ht 7 re
7--sum()函數(shù)
7--實(shí)例解釋
基本語(yǔ)法
sum(iterable, start)
iterable--可迭代對(duì)象,例如:列表,元組,集合
start--指定相加的對(duì)象,如果沒(méi)設(shè)定默認(rèn)為0
實(shí)例 # 基本操作
print(sum(range(1,11))) # 求1~10的和 --55
print(sum(range(1,11), 10)) # 求1~10的和之后 在+10 --65
#嵌套操作 # 求1-2+3-4+5-6+7-8+9-10+11......-100和
求偶數(shù)之和 a = sum(range(1,101)[1::2])
求奇數(shù)之和 b = sum(range(1,101)[::2])
根據(jù)題意: 偶數(shù)求和之后是負(fù)數(shù) a = -sum(range(1,101)[1::2])
然后根據(jù) 對(duì)a,b求和 sum(a,b)# 錯(cuò)誤
sum([a,b])
print(sum([sum(range(1,101)[::2]), -sum(range(2,101)[::2])]))
8--set()函數(shù)
8--實(shí)例解釋
set()函數(shù)創(chuàng)建一個(gè)沒(méi)有重復(fù)元素集,可以進(jìn)行關(guān)系測(cè)試,刪除重復(fù),還可以計(jì)算交集并集..
set(iterable) iterable---可迭代對(duì)象
返回值----集合
實(shí)例 # 基本操作
a = set("hello") #輸出--{'h','l','e','o'}
b = set("python") #輸出--{'p','y','t','h','o','n'}
a & b #交集
{'h','o'}
a | b #并集
{'h', 'y', 'p', 'e', 'o', 'n', 'l', 't'} # 也會(huì)去掉重復(fù)元素
9--join()方法
9--實(shí)例解釋
Python join() 方法用于將序列中的元素以指定的字符連接生成一個(gè)新的字符串
語(yǔ)法
join()方法語(yǔ)法:
str.join(sequence)
sequence -- 要連接的元素序列
返回通過(guò)指定字符連接序列中元素后生成的 新字符串!!!
實(shí)例 # 基本使用
s1 = "-"
s2 = ""
seq = ("r", "u", "n", "o", "o", "b") # 字符串序列
print(s1.join(seq))
print(s2.join(seq))
10--split()方法
10--實(shí)例解釋
split()方法通過(guò)指定的字符串進(jìn)行切片分割,如果有num有指定的值,則分割num次數(shù)
基本語(yǔ)法
str1.split(str2, num)
str1 要分割的字符串, str2 要分割的符號(hào), num要分割的次數(shù)
實(shí)例 # 基本操作
str = "this is string example...wow!!!"
str.split() 或者 str.split(' ') #輸出 ['this','is','string','example...wow!!!']
str.split('i', 1) #輸出 ['th','s is string example...wow!!!']
11--replace()方法
11--實(shí)例解釋
把字符串的舊字符換成新字符
str.replace(old, new)
old -- 舊字符
new -- 新字符
num -- 替換的次數(shù)
str = "this is string example...wow!!!"
str.replace('is', 'was') # 輸出 "thwas was string example...wow!!!"
12--format()方法
12--實(shí)例解釋
# 不設(shè)置指定位置,按默認(rèn)順序
"{} & {}".format("hello", "world", "python")
'hello world'
# 設(shè)置指定位置
>>> "{0} {1}".format("hello", "world")
'hello world'
# 設(shè)置指定位置
>>> "{1} {0} {1}".format("hello", "world")
'world hello world'
# 二進(jìn)制
>>> '{0:b}'.format(10)
'1010'
#八進(jìn)制
>>> '{0:o}'.format(10)
'12'
#16進(jìn)制
>>> '{0:x}'.format(10)
'a'
實(shí)例 # 基本操作
print('{} & {}'.format('I, Love',Python))
輸出I, Love & Python
13--eval()函數(shù)
13--實(shí)例解釋
eval()函數(shù) 將字符串str當(dāng)成有效的表達(dá)式求值并返回結(jié)果
實(shí)例 # 基本操作
# 基本的數(shù)學(xué)計(jì)算
In [1]: eval("1 + 1")
Out[1]: 2
# 字符串重復(fù)
In [2]: eval("'*' * 10")
Out[2]: '**********
# 用eval()計(jì)算階乘
print(eval('*'.join([str(n) for n in range(1, 5)])))
# eval函數(shù)就是實(shí)現(xiàn)list、dict、tuple與str之間的轉(zhuǎn)化
# str函數(shù)把list,dict,tuple轉(zhuǎn)為為字符串
# 字符串轉(zhuǎn)換成列表
a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]"
print(type(a)) # 字符串
b = eval(a) #
print(b) # [[1,2], [3,4], [5,6], [7,8], [9,0]]
# 字符串轉(zhuǎn)換成字典
a = "{1: 'a', 2: 'b'}"
print(type(a)) # 字符串
b = eval(a)
print(type(b)) # 字典
print(b) # {1: 'a', 2: 'b'}
# 字符串轉(zhuǎn)換成元組
a = "([1,2], [3,4], [5,6], [7,8], (9,0))"
print(type(a)) # 字符串
b = eval(a)
print(type(b)) # 元組
print(b) # ([1,2], [3,4], [5,6], [7,8], (9,0))