Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
796 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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])) 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...