统计字符(python)

统计下面三引号封闭的这一段英文中出现频率最高的3个字符(包括空格、标点符号在内):""“The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images.”""。

s = """The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images."""
stat = [(ch, s.count(ch)) for ch in set(list(s))]
print(stat)
print(sorted(stat, key = lambda x:x[1])[-3:])
print(sorted(stat, key = lambda x:x[1], reverse=True)[:3])
sort() 函数

语法:list.sort( key=None, reverse=False)

  • 将列表中的元素进行排序。默认按升序排列。
  • reverse参数:指明列表是否降序排列,若等于True表示降序排序,默认为False。
  • 如果列表中包含的是字符串,按字母串排序规则排序。
  • 可以使用key参数来指定排序方式。
sorted() 函数
  • 对列表进行排序并返回新列表。

sort 是应用在 list 上的方法,sorted 可以对所有可迭代的对象进行排序操作。

list 的 sort 方法返回的是对已经存在的列表进行操作,无返回值,而内建函数 sorted 方法返回的是一个新的 list,而不是在原来的基础上进行的操作。

sorted(iterable, cmp=None, key=None, reverse=False)

  • iterable – 可迭代对象。
  • cmp – 比较的函数,这个具有两个参数,参数的值都是从可迭代对象中取出,此函数必须遵守的规则为,大于则返回1,小于则返回-1,等于则返回0。
  • key – 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
  • reverse – 排序规则,reverse = True 降序 , reverse = False 升序(默认)。
lambda函数

参考:https://blog.csdn.net/zjuxsl/article/details/79437563

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值