1、如何统计一篇文章中出现频率最高的 5 个单词?
import re
d={}
str='If we want to" run Locust \ / distributed on multiple machines we would also have to specify the master host when starting the slaves (this is not needed when running Locust distributed on a single machine, since the master host defaults to ):'
l = re.split("\W+", str.lower())
for i in l:
if len(i):
pass
else:
del l[l.index(i)]
for i in l:
d[i] = l.count(i)
z=sorted(d.items(),key=lambda x:x[1],reverse=True)
print(d,z)
2、map 映射函数按规律生成列表或集合?
map(function, iterable, ...)
function:映射函数
iterable:参数序列,可迭代对象,可接受多个
例子:
l=[1,2,3,4]
x=[5,6,7,8]
l = list(map(lambda x:x*2, l))
z=list(map(lambda x,y:x+y, l, x))
3、filter 过滤函数如何使用?如何过滤奇数偶数平方根数?
filter(function, iterable)
两个参数,第一个参数function,过滤函数,筛选符合条件;第二个参数iterable,序列中的每个元素依次传递给function进行过滤
l=[1,2,3,4,5,6,7,8,9]
l = list(filter(lambda x:x%2==0, l))
4、sort 和 sorted 排序函数的用法区别?
sort()是列表独有的,能够对列表进行排序,无返回值,直接对列表进行修改
sorted(iterable)只要是可迭代对象都可以使用,接收可迭代对象为参数,返回一个排序好的迭代器
5、enumerate 为元素添加下标索引?
l=[1,2,3,4,5,6]
for k,v in enumerate(l):
print(k,v)
6、lambda 匿名函数如何使用?
lambda x:x+2
7、type 和 help 函数有什么作用?
type():查看参数的类型
help():查看函数、模块等的具体用法