標籤:.net abs rabl ace 相同 value target arp lambda
#max() array1 = range(10) array2 = range(0, 20, 3) print(‘max(array1)=‘, max(array1)) print(‘max(array2)=‘, max(array2)) print(‘max(array1,)=‘, max(array1, key=lambda x: x > 3) ) print(max(1, 2)) print(max(‘ah‘, ‘bf‘, key=lambda x: x[1])) print(max(array1, array2, key=lambda x: x[1])) def comparator(x): return x[2] print(max(‘ah2‘, ‘bf3‘, key=comparator)) 結果輸出如下:max(array1)= 9max(array2)= 18max(array1,)= 42ahrange(0, 20, 3)bf3
說明:
1. 函數功能為取傳入的多個參數中的最大值,或者傳入的可迭代對象元素中的最大值。預設數值型參數,取值大者;字元型參數,取字母表排序靠後者。還可以傳入具名引數key,其為一個函數,用來指定取最大值的方法。default具名引數用來指定最大值不存在時返回的預設值。
2. 函數至少傳入兩個參數,但是有只傳入一個參數的例外,此時參數必須為可迭代對象,返回的是可迭代對象中的最大元素。
>>> max(1) # 傳入1個參數報錯Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> max(1)TypeError: ‘int‘ object is not iterable>>> max(1,2) # 傳入2個參數 取2個中較大者2>>> max(1,2,3) # 傳入3個參數 取3個中較大者3>>> max(‘1234‘) # 傳入1個可迭代對象,取其最大元素值‘4‘
3. 當傳入參數為資料類型不一致時,傳入的所有參數將進行隱式資料類型轉換後再比較,如果不能進行隱式資料類型轉換,則會報錯。
>>> max(1,1.1,1.3E1) # 整數與浮點數可取最大值13.0>>> max(1,2,3,‘3‘) # 數值與字串不能取最大值Traceback (most recent call last): File "<pyshell#5>", line 1, in <module> max(1,2,3,‘3‘)TypeError: unorderable types: str() > int() >>> max([1,2],[1,3]) # 列表與列表可取最大值[1, 3]>>> max([1,2],(1,3)) # 列表與元組不能取最大值Traceback (most recent call last): File "<pyshell#7>", line 1, in <module> max([1,2],(1,3))TypeError: unorderable types: tuple() > list()
4. 當存在多個相同的最大值時,返回的是最先出現的那個最大值。
#定義a、b、c 3個列表>>> a = [1,2]>>> b = [1,1]>>> c = [1,2] #查看a、b、c 的id>>> id(a)68128320>>> id(b)68128680>>> id(c)68128240 #取最大值>>> d = max(a,b,c)>>> id(d)68128320 #驗證是否最大值是否是a>>> id(a) == id(d)True
5. 預設數值型參數,取值大者;字元型參數,取字母表排序靠後者;序列型參數,則依次按索引位置的值進行比較取最大者。還可以通過傳入具名引數key,指定取最大值方法。
>>> max(1,2) # 取數值大者2>>> max(‘a‘,‘b‘) # 取排序靠後者‘b‘>>> max(‘ab‘,‘ac‘,‘ad‘) # 依次按索引比較取較大者‘ad‘ >>> max(-1,0) # 數值預設去數值較大者0>>> max(-1,0,key = abs) # 傳入了求絕對值函數,則參數都會進行求絕對值後再取較大者-1
6. key參數的另外一個作用是,不同類型對象本來不能比較取最大值的,傳入適當的key函數,變得可以比較能取最大值了。
>>> max(1,2,‘3‘) #數值和字串不能取最大值Traceback (most recent call last): File "<pyshell#21>", line 1, in <module> max(1,2,‘3‘)TypeError: unorderable types: str() > int()>>> max(1,2,‘3‘,key = int) # 指定key為轉換函式後,可以取最大值‘3‘ >>> max((1,2),[1,1]) #元組和列表不能取最大值Traceback (most recent call last): File "<pyshell#24>", line 1, in <module> max((1,2),[1,1])TypeError: unorderable types: list() > tuple()>>> max((1,2),[1,1],key = lambda x : x[1]) #指定key為返回序列索引1位置的元素後,可以取最大值(1, 2)複製代碼
7. 當只傳入的一個可迭代對象時,而且可迭代對象為空白,則必須指定具名引數default,用來指定最大值不存在時,函數返回的預設值。
>>> max(()) #空可迭代對象不能取最大值Traceback (most recent call last): File "<pyshell#26>", line 1, in <module> max(())ValueError: max() arg is an empty sequence>>> max((),default=0) #空可迭代對象,指定default參數為預設值0>>> max((),0) #預設值必須使用具名引數進行傳參,否則將被認為是一個比較的元素Traceback (most recent call last): File "<pyshell#27>", line 1, in <module> max((),0)TypeError: unorderable types: int() > tuple()
原文地址:http://www.jb51.net/article/97571.htm
【轉】Python max內建函數詳細介紹