开发者

Python sorting a file by frequency

开发者 https://www.devze.com 2023-03-03 11:34 出处:网络
I have a file that contains a list of words like: word1 34 word2 12 word3 6 word4 498 word5 50 I want to sort the file by the numerical value. My code:

I have a file that contains a list of words like:

word1 34

word2 12

word3 6

word4 498

word5 50

I want to sort the file by the numerical value. My code:

sortedfreqlist = sorted(freqlist, key=operator.itemgetter(1), reverse=True)

Doesn't quite work bec开发者_开发问答ause it sorts the numbers as words i.e 12 comes before 6 etc.

Any ideas how I can do this?


The sorting is not working because your values are not of a numeric type, thus lexicographic sorting is applied. Be sure to convert your sort key to to a number, for example like this:

sortedfreqlist = sorted(freqlist, key=lambda item: int(item[1]), reverse=True)


Search "natural sort python" in your favorite search engine and you'll find many different solutions.

Here is one at activestate.

Here is a nice tidy solution at SO.

0

精彩评论

暂无评论...
验证码 换一张
取 消