Reputation: 7924
I am looking for a way to select the major value in a list of numbers in order to get the attributes.
data
[(14549.020163184512, 58.9615170298556),
(18235.00848249135, 39.73350448334156),
(12577.353023695543, 37.6940001866714)]
I wish to extract (18235.00848249135, 39.73350448334156) in order to have 39.73350448334156. The previous list (data) is derived from a a empty list data=[]. Is it the list the best format to store data in a loop?
Upvotes: 0
Views: 701
Reputation: 187
You can actually sort on any attribute of the list. You can use itemgetter. Another way to sort would be to use a definitive compare functions (when you might need multiple levels of itemgetter, so the below code is more readable).
dist = ((1, {'a':1}), (7, {'a': 99}), (-1, {'a':99}))
def my_cmp(x, y):
tmp = cmp(x[1][a], y[1][a])
if tmp==0:
return (-1 * cmp(x[0], y[0]))
else: return tmp
sorted = dist.sort(cmp=my_cmp) # sorts first descending on attr "a" of the second item, then sorts ascending on first item
Upvotes: 1
Reputation: 212835
max(data)[1]
Sorting a tuple sorts according to the first elements, then the second. It means max(data)
sorts according to the first element.
[1]
returns then the second element from the "maximal" object.
Upvotes: 2
Reputation: 8726
You can get it by :
max(data)[1]
since tuples will be compared by the first element by default.
Upvotes: 3