首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >怎样计算argmax?

怎样计算argmax?
EN

Stack Overflow用户
提问于 2014-01-29 02:14:39
回答 2查看 489关注 0票数 2

如果我有一个列表和一个计算分数的函数,我可以这样计算argmax:

代码语言:javascript
复制
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吗?怎样才能做到这一点呢?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-01-29 02:20:35

代码语言:javascript
复制
def score(i):
    return sum([int(j) for j in str(i) if j.isdigit()])

max(x, key=score)
票数 8
EN

Stack Overflow用户

发布于 2014-01-29 03:47:18

如果要对非Unicode字符串的大型列表执行大量此操作,那么设置这些字符串的一次性开销可能是值得的,因此可以通过相对简单的表查找和用C编写的内置方法来完成尽可能多的过程(正如string_translate()在CPython中所做的那样):

代码语言:javascript
复制
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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21420800

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档