值排序为字符串,但我想在 Python 中将它们排序为数字 [英] Values sorted as String but I want to sort them as number in Python
问题描述
我在 python 中读取了一个日志,其中包含每行的名称、内存、ncalls并将其保存为元组列表,其中每个元素都是一个元组 (name, memory, ncalls)有时需要根据名称对列表进行排序,有时需要根据内存或 ncalls.如果我只是使用代码的问题
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))
使用所需的参数对列表进行排序,但python将参数视为字符串,我得到了这个结果
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
想要的结果是
item3, 45, 1
item4, 65, 3
item2, 65, 5
item1, 4, 12
因为 3 和 5 小于 12
because 3 and 5 are smaller than 12
如何在不改变我保存列表的方式的情况下解决这个问题?
How could I solve this without change the way i save the list?
推荐答案
一个解决方案是将 key 定义为将第三项转换为 int 的 lambda:
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]))
这篇关于值排序为字符串,但我想在 Python 中将它们排序为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!