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