今天学习了三元表达式、递归(一般作用于文件)、二分法(更高效的从列表、字典...中查找数据)、datetime与random模块
三元表达式:
语法:结果a if 条件 else 结果b(为Ture时返回结果啊,为False时返回结果b)
a = 10 b = 20 print(a if a > b else b)
递归:
"""
递归:函数自己调用自己
os.listdir() 获取路径下的全部文件,返回list列表
os.path.join(path, name) 拼接出完整的文件路径
os.path.isdir() 判断是否是目录
"""
print("递归:")
import os
def read(path,flo):
lst = os.listdir(path)
for name in lst:
real_path = os.path.join(path,name)
if os.path.isdir(real_path):
print("t"*flo, name)
read(real_path, flo+1)
else:
print("t"*flo, name)
read("a",0)
结果:
二分法:
"""
二分法(必须是有序的列表)
优点:可以更快的从一大片数据中找到所需的
原理:一直以该数所在的区域的2/1来切割取数。
"""
list = [11, 22, 33, 44, 55, 66, 77, 88, 99, 110]
min = 0
max = len(list) - 1
num = int(input("请输入要查找的数:"))
while min <= max:
pos = (max + min) // 2 # 在Python中/表示浮点整除法,返回浮点结果,也就是结果为浮点数;而//在Python中表示整数除法,返回大于结果的一个最大的整数,意思就是除法结果向下取整。
if num > list[pos]:
min = pos + 1 #因为pos的位置已经不是要找的数了。所以要pos+1到下一个数来切割
elif num < list[pos]:
max = pos - 1 #因为pos的位置已经不是要找的数了。所以要pos-1到上一个数来切割
else:
print("找到了,该数的位置是:", pos)
break
else:
print("没找到")
结果:
模块:
import time #导入一个模块整体
from time import sleep #从一个模块中导入一个具体的功能
"""
datetime模块
datetime:年月日,时分秒
date:年月日
time:时分秒
#time.sleep() 可以暂停执行一段时间
#time.time() 时间戳。从1970-01-01 00:00:00到现在的秒数 (数字类型的时间)。可以计算小的时间差
frmm datetime import datetime
from datetime import date
datetime.now() 获取当前时间
datetime(2018, 1, 2, 12, 12, 13) 输出:2018-1-12 12:12:13
total_seconds() 得到时间差。单位:秒
strftime(“%Y年%m月%d日 %H小时%M分钟%S秒”) 把时间格式化成字符串
datetime.strptime(字符串, "格式") 把字符串转化成时间
date.today() 日期
"""
"""
random模块
random.random() 得到0~1的随机小数
random.uniform(数字1, 数字2) 得到随机小数
random.randint(数字1, 数字2) 随机整数,能够取到边界
random.choice(列表) 随机从列表中选择一个
random.sample(列表, 数量) 随机从列表中选出指定数量
"""



