统计下面三引号封闭的这一段英文中出现频率最高的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 升序(默认)。