Values sorted as String but I want to sort them as number in Python

老子叫甜甜 提交于 2021-02-04 08:19:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!