內(nèi)置函數(shù)-----filter和map
例如,要從一個(gè)list [1, 4, 6, 7, 9, 12, 17]中刪除奇數(shù),保留奇數(shù),首先,要編寫(xiě)一個(gè)判斷奇數(shù)的函數(shù)
def add(x):
return x % 2 == 1
然后,利用filter()過(guò)濾掉偶數(shù)
a = filter(add, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
filter()過(guò)濾掉偶數(shù)后的結(jié)果
print(list(a))
#[1, 3, 5, 7, 9]
利用filter(),可以完成很多有用的功能,例如,刪除 None 或者空字符串
def is_not_empty(s):
return s and len(s.strip()) > 0
r = filter(is_not_empty,['sts', None, ' '])
print(list(r))
注意: s.strip(rm) 刪除 s 字符串中開(kāi)頭、結(jié)尾處的 rm 序列的字符。
當(dāng)rm為空時(shí),默認(rèn)刪除空白符(包括'\n', '\r', '\t', ' '),如下:
a = '123 '
print(a.strip())
a = '\t\t\n123\t\t\n\n'
print(a.strip())
請(qǐng)利用filter()過(guò)濾出1~100中平方根是整數(shù)的數(shù),即結(jié)果應(yīng)該是:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
import math # 導(dǎo)入數(shù)學(xué)常量
def is_sqr(x):
return math.sqrt(x) % 1 == 0 # .sqrt為開(kāi)根號(hào)
s = filter(is_sqr, range(1, 101))
print(list(s))
有一個(gè)list, L = [1,2,3,4,5,6,7,8],我們要將f(x)=x^2作用于這個(gè)list上,那么我們可以使用map函數(shù)處理。
L = [1,2,3,4,5]
def is_square(x):
return x * x
s = map(is_square,L)
print(list(s))
對(duì)List、Dict進(jìn)行排序,Python提供了兩個(gè)方法 對(duì)給定的List L進(jìn)行排序, 方法1.用List的成員函數(shù)sort進(jìn)行排序,在本地進(jìn)行排序,不返回副本 方法2.用built-in函數(shù)sorted進(jìn)行排序(從2.4開(kāi)始),返回副本,原始輸入不變
--------------------------------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.
-----------------------------------------------------------------------------
參數(shù)說(shuō)明: iterable:是可迭代類(lèi)型;
key:傳入一個(gè)函數(shù)名函數(shù)的參數(shù)是可迭代類(lèi)型中的每一項(xiàng),根據(jù)函數(shù)的返回值大小排序; reverse:排序規(guī)則. reverse = True 降序 或者 reverse = False 升序,有默認(rèn)值。
返回值:有序列表
例子
l1 = [-1,2,-2,-4,0,1,3,5,7]
l2 = sorted(l1,key=abs)
print(l1)
print(l2)
l = ['1','2',[1,2,3],'sssssss']
l2 = sorted(l,key=len)
print(l2)
匿名函數(shù)
匿名函數(shù)格式
函數(shù)名 = lambda 參數(shù) :返回值
#參數(shù)可以有多個(gè),用逗號(hào)隔開(kāi)
#匿名函數(shù)不管邏輯多復(fù)雜,只能寫(xiě)一行,且邏輯執(zhí)行結(jié)束后的內(nèi)容就是返回值
#返回值和正常的函數(shù)一樣可以是任意數(shù)據(jù)類(lèi)型
請(qǐng)把以下函數(shù)變成匿名函數(shù)
def add(x,y):
return x+y
結(jié)果
kkk = lambda x, y: x+y
上面是匿名函數(shù)的函數(shù)用法。除此之外,匿名函數(shù)也不是浪得虛名,它真的可以匿名。在和其他功能函數(shù)合作的時(shí)候
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
res = filter(lambda x:x>10,[5,8,11,9,15])
for i in res:
print(i)
# 輸出
# 11
# 15
聯(lián)系客服