2014-01-29 96 views
2

如果我有一個列表和一個函數來計算分數,我可以計算argmax這樣:什麼是計算argmax的pythonic方法?

maxscore = 0; argmax = None 
x = [3.49, 0.122, 293, 0.98] # Imagine a LARGE list. 
for i in x: 
    # Maybe there're some other func() to calculate score 
    # For now just sum the digits in i. 
    score = sum([int(j) for j in str(i) if j.isdigit()]) 
    print i, score 
    if maxscore < score: 
     maxscore = score 
     argmax = i 

是否有任何其他的方式來實現argmax?什麼是pythonic方式這樣做?

回答

8
def score(i): 
    return sum([int(j) for j in str(i) if j.isdigit()]) 

max(x, key=score) 
+0

好得多,我沒有看過他的代碼足夠接近:P –

0

如果你要這樣的非Unicode字符串的大名單做了很多,但可能值得設置一些事情,從而儘可能多的過程中的一次性開銷儘量可以做到通過用C寫的比較簡單的表查找和內置方法(如string_translate()是CPython的):

x = [3.49, 0.122, 293, 0.98] 

digits = set(range(ord('0'), ord('9')+1)) 
transtable = ''.join(chr(i-ord('0')) if i in digits else chr(0) 
         for i in range(256)) 
deletechars = ''.join(chr(i) for i in range(256) if i not in digits) 

def sum_digit_chars(i): 
    return sum(bytearray(str(i).translate(transtable, deletechars))) 

print max(x, key=sum_digit_chars) 
相關問題