2

如果我有一个列表和一个函数来计算分数,我可以这样计算 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方法是什么?

4

2 回答 2

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

max(x, key=score)
于 2014-01-29T02:20:35.980 回答
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)
于 2014-01-29T03:47:18.517 回答