开发者

UPDATE:Sorting a list from a for output from highest to lowest in python

开发者 https://www.devze.com 2023-03-03 21:50 出处:网络
for x in letters: frequency[x]+=1 for x in frequency: print x,frequency[x],frequency[x]/float(n) Sorry but I\'m fairly new to programming and everything and I\'m trying to get the output to be sorte
    for x in letters:
         frequency[x]+=1
    for x in frequency:
        print x,frequency[x],frequency[x]/float(n)    

Sorry but I'm fairly new to programming and everything and I'm trying to get the output to be sorted from highest value of frequency[x]/float(n) to lowest value. Is there any method of being 开发者_开发百科able to sort it just through the printing command?

Thanks very much!


For the keys:

sorted(frequency, key=lambda x: frequency[x], reverse=True)


Do

for x in sorted(frequency, key=lambda y: frequency[y]/float(n), reverse=True):
    print x,frequency[x],frequency[x]/float(n)


This should do the trick:

freqs = sorted([frequency[x]/float(n) for x in frequency], reverse=True)

If you want it more like the print statement you have above, try this:

for (fxn, fx, x) in sorted([(frequency[x]/float(n), frequency[x], x) for x in frequency], reverse=True):
    print x, fx, fxn


Answers flashing right before my eyes! Yes, use sorted. Read more here.

0

精彩评论

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