如果我有一个列表和一个计算分数的函数,我可以计算argmax:
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方式呢?
答案 0 :(得分:8)
def score(i):
return sum([int(j) for j in str(i) if j.isdigit()])
max(x, key=score)
答案 1 :(得分:0)
如果您要为大型非Unicode字符串列表做很多事情,那么设置的一次性开销可能是值得的,因为尽可能多的过程可以通过相对简单的表来完成-lookups和用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)