如果我有一个列表和一个计算分数的函数,我可以这样计算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吗?怎样才能做到这一点呢?
发布于 2014-01-29 02:20:35
def score(i):
return sum([int(j) for j in str(i) if j.isdigit()])
max(x, key=score)发布于 2014-01-29 03:47:18
如果要对非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)https://stackoverflow.com/questions/21420800
复制相似问题