Board logo

标题: [问题求助] Python怎样找出字符串中出现次数最多的字符? [打印本页]

作者: Python    时间: 2013-6-22 09:23     标题: Python怎样找出字符串中出现次数最多的字符?

Python怎样找出字符串中出现次数最多的字符?
已知字符串:
a = "aAsmr3idd4bgs7Dlsf9eAF"
希望找到出现次数最多的字符及其出现的次数:
3 : s
作者: ShadowFiend    时间: 2013-6-22 10:42

  1. # -*- coding: utf-8 -*-
  2. # Python 3.3.1
  3. _str = "aAsmr3idd4bgs7Dlsf9eAF"
  4. count = {}
  5. for _item in sorted(list(_str)):
  6.     if _item in count:
  7.         count[_item] += 1
  8.     else:
  9.         count[_item] = 1
  10.         
  11. print(sorted([(count,word) for word,count in count.items()],reverse=True)[0])
  12. input()
复制代码

作者: Batcher    时间: 2013-6-23 11:04

  1. def fun(a):
  2.     return a[1]
  3. a = "aAsmr3idd4bgs7Dlsf9eAF"
  4. l = ([(x, a.count(x)) for x in set(a)])
  5. l.sort(key = fun, reverse=True)
  6. print "%s : %s" % (l[0][1], l[0][0])
复制代码

作者: Batcher    时间: 2013-6-23 11:05

  1. a = "aAsmr3idd4bgs7Dlsf9eAF"
  2. l = ([(x, a.count(x)) for x in set(a)])
  3. b = 3
  4. l.sort(key = lambda l: l[1] + b, reverse=True)
  5. print "%s : %s" % (l[0][1], l[0][0])
复制代码





欢迎光临 批处理之家 (http://bbs.bathome.net/) Powered by Discuz! 7.2