Python Tutorial

Sunday, September 28, 2014

Min, max value and index from list

See also enumerate and operator.itemgetter
import operator
a = [2, 5, 1, 4, 8, 71, 4, 1, 21]
min_i, min_v = min(enumerate(a), key = operator.itemgetter(1))
max_i, max_v = max(enumerate(a), key = operator.itemgetter(1))

print "[Min] index:",min_i,"value:",min_v
print "[Max] index:",max_i,"value:",max_v


Output:
[Min] index: 2 value: 1
[Max] index: 5 value: 71

0 comments:

Post a Comment