函数与模块

mac2024-03-11  24

lambda 匿名函数

#lambda 作为匿名函数,是不需要函数名的→需要一个函数,又不想动脑筋取想名字,这就是匿名函数 #lambda的主体是一个表达式,而不是一个代码块 #lambda只有一行,仅仅能在lambda表达式中封装有限的逻辑进去 def fun(a,b,c): return a+b+c print(fun(1,2,3)) f = lambda a,b,c:a+b+c print(f(1,2,3)) f = lambda num:len(num) print(f([1,2,3,4,5,6,'l']))

列表排序函数两种写法

def f(list): list.sort return list print(f([3,1,2,55])) def f(*var): st = list(var) st_re = sorted(st,reverse=True) return(st_re) print(f(1,2,6,4,2,3,6))

字符串各类型元素计数

st = 'abcndjd de' len(st) a = 0 b = 0 c = 0 d = 0 for n in range(0,len(st)-1): if st[n].isalpha(): a += 1 elif st[n].isspace(): b += 1 elif st[n].isdigit(): c += 1 else: d += 1 print(a,b,c,d)

模块路径的问题

查看现有包所在的路径,将自己创建的包存入该路径中加载sys包,把新建的testmodel模块放在的路径添加上 import pandas print(pandas.__file__) # 将新建模块放入下面的文件路径中 C:\Users\Administrator\Anaconda3\lib\site-packages\pandas\__init__.py import sys sys.path.append('C://Users/desktop/') # 加载sys包,将新建模块所在路径添加上

time 模块

# time模块 import time for i in range(5): print('hello') time.sleep(1) #休眠 print(time.ctime()) #当前时间 print(type(time.ctime())) print(time.localtime()) #当地时间 print(type(time.localtime())) print(time.strftime('%y-%m-%d %H:%M:%S',time.localtime())) #按指定格式输出时间 print(type(time.strftime('%y-%m-%d %H:%M:%S',time.localtime()))) result: hello hello hello hello hello Thu Oct 31 08:11:07 2019 <class 'str'> time.struct_time(tm_year=2019, tm_mon=10, tm_mday=31, tm_hour=8, tm_min=11, tm_sec=7, tm_wday=3, tm_yday=304, tm_isdst=0) <class 'time.struct_time'> 19-10-31 08:11:07 <class 'str'>

random模块

# random 模块 import random x = random.random() #输出0到1的随机数 y = random.random() print(x,y*100) m = random.randint(0,20) #输出指定范围内1个整数 print(m) lst = list(range(20)) s = random.choice(lst) #列表中选择一个数 print(s) sli = random.sample(lst,5) #列表中选择5个数 print(sli) random.shuffle(lst) #列表打乱 print(lst)
最新回复(0)