标题: [问题求助] Python怎样找出字符串中出现次数最多的字符? [打印本页]
作者: Python 时间: 2013-6-22 09:23 标题: Python怎样找出字符串中出现次数最多的字符?
Python怎样找出字符串中出现次数最多的字符?
已知字符串:
a = "aAsmr3idd4bgs7Dlsf9eAF"
希望找到出现次数最多的字符及其出现的次数:
3 : s
作者: ShadowFiend 时间: 2013-6-22 10:42
- # -*- coding: utf-8 -*-
- # Python 3.3.1
-
- _str = "aAsmr3idd4bgs7Dlsf9eAF"
- count = {}
-
- for _item in sorted(list(_str)):
- if _item in count:
- count[_item] += 1
- else:
- count[_item] = 1
-
-
- print(sorted([(count,word) for word,count in count.items()],reverse=True)[0])
-
- input()
复制代码
作者: Batcher 时间: 2013-6-23 11:04
- def fun(a):
- return a[1]
-
- a = "aAsmr3idd4bgs7Dlsf9eAF"
- l = ([(x, a.count(x)) for x in set(a)])
-
- l.sort(key = fun, reverse=True)
- print "%s : %s" % (l[0][1], l[0][0])
复制代码
作者: Batcher 时间: 2013-6-23 11:05
- a = "aAsmr3idd4bgs7Dlsf9eAF"
- l = ([(x, a.count(x)) for x in set(a)])
-
- b = 3
- l.sort(key = lambda l: l[1] + b, reverse=True)
- print "%s : %s" % (l[0][1], l[0][0])
复制代码
欢迎光临 批处理之家 (http://bbs.bathome.net/) |
Powered by Discuz! 7.2 |