[英]Find the largest numeric string from a list
我有一個清單。 我想找到最大數量,但是我在下面的代碼中嘗試了錯誤的最大數量
list1=['400160', '400161', '400162', '400163', '400164', '400165', '400166', '400167', '400168', '400169', '400170', '400171', '400172', '400173', '400174', '400175', '400176', '400177','99990', '99991', '99992', '99993', '99994', '99995', '99996', '99997', '99998', '99999']
list1.sort()
#printing the last element
print("Largest element is:", list1[-1])
#print max(list1)
我的輸出如下:
print("Largest element is:", list1[-1])
('Largest element is:', '99999')
但這是錯誤的。 如何找到最大數量
使用max
的key
參數是另一種明智的方法。
max(list1, key=int)
# '400177'
請注意,您不必事先對list1
進行排序,在最壞的情況下,找到最大值永遠不會比O(N)復雜。
當前輸出的原因是因為您在字符串列表上調用list.sort
。 默認情況下, sort
將按字典順序比較字符串,並且'9'>'4'。
將strings
轉換為int
並找到max
:
max(map(int, list1))
400177
現在,您正在比較一個字符串列表,該排序按字典順序進行,如果以這種方式排序,則'99999'
是按字典順序排列的最大值
因此,您需要字符串列表第一個轉換為數字的列表,然后用最大內置找到最大。
排序列表以找到最大值可能是一個過大的殺傷力。
排序+最大發現將為O(n*logn)
而僅找到最大將為O(n)
In [40]: list1=['400160', '400161', '400162', '400163', '400164', '400165', '400166', '400167', '400168', '400169', '400170', '400171', '400172', '400173', '400174', '400175', '400
...: 176', '400177','99990', '99991', '99992', '99993', '99994', '99995', '99996', '99997', '99998', '99999']
In [41]: list1 = list(map(int,list1))
In [43]: max(list1)
Out[43]: 400177
應該使用map
和max
。 像這樣:
list1=['400160', '400161', '400162', '400163', '400164', '400165', '400166', '400167', '400168', '400169', '400170', '400171', '400172', '400173', '400174', '400175', '400176', '400177','99990', '99991', '99992', '99993', '99994', '99995', '99996', '99997', '99998', '99999']
print(max(map(int, list1)))
輸出:
>>>python3 test.py
400177
應該這樣做:
max(map(int, list1))
您必須先將項目從str
轉換為int
。 我在這里使用map(int, list1)
此操作,該方法將int()
應用於list1
每個項目。
打印“最大的元素是:”,最大值(map(int,list1))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.