问题
I read in python a log that contains name, memory, ncalls for each row and save this as tuple list where each element is a tuple (name, memory, ncalls) sometimes need to sort the list according name other times according memory or ncalls. The problem if I simply use the code
mylist=sorted(mylist, key=itemgetter(2))
the list is sorted using the desired parameter but python consider the parameter like a String and I get this result
item3, 45, 1
item1, 4, 12
item4, 65, 3
item2, 65, 5
the desired result would be
item3, 45, 1
item4, 65, 3
item2, 65, 5
item1, 4, 12
because 3 and 5 are smaller than 12
How could I solve this without change the way i save the list?
回答1:
A solution is to define key as a lambda converting the third item to int:
sorted_data = sorted(list, key=lambda t: int(t[2]))
来源:https://stackoverflow.com/questions/36399303/values-sorted-as-string-but-i-want-to-sort-them-as-number-in-python