python降序输出-python 根据两个字段排序, 一个升序, 一个降序

给定一个字符串, 输出出现次数最多的前三个字符, 若两字符出现次数相同, 则按字典顺序排列.

# 样例输入

aabbbccde

# 样例输出

b 3

a 2

c 2

就是先将第二字段降序排序, 再将第一字段升序排序, 关键就是sorted函数key的指定, 可以用 lambda 或

operator.itemgetter

开始我是这样做的:

from collections import Counter

c = Counter(input())

l=sorted(c.items(), key=lambda s:(-s[1], s[0]))

for i in l[:3]:

print(" ".join(map(str, list(i))))

EDITORIAL给出了三个参考解:

1.利用字母表

S = raw_input()

letters = [0]*26

for letter in S:

letters[ord(letter)-ord("a")] += 1

for _ in range(3):

max_letter = max(letters)

for index in range(26):

if max_letter == letters[index]:

print chr(ord("a")+index), max_letter

letters[index] = -1

break

2.

from collections import Counter

from operator import itemgetter

for item in (sorted(sorted(Counter(raw_input()).items()), key = itemgetter(1), reverse = True)[:3]):

print item[0], item[1]

3.

from collections import Counter

for letter, counts in sorted(Counter(raw_input()).most_common(),key = lambda x:(-x[1],x[0]))[:3]:

print letter, counts most_common 的行为可能在python 2和3之间不同, 没仔细研究

参考:

http://blog.chinaunix.net/xmlrpc.php?r=blog/article&uid=429659&id=3140368

http://stackoverflow.com/questions/6666748/python-sort-list-of-lists-ascending-and-then-decending

http://stackoverflow.com/questions/5212870/sorting-a-python-list-by-two-criteria

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值