常用内置模块collections模块
1.具名元组
| from collections import namedtuple |
| |
| |
| n1 = namedtuple('车', ('num name')) |
| res1 =n1(1, '轿车') |
| res2 =n1(2,'老爷车') |
| print(res1,res2) |
| print(res1.num, res2.name) |
| |
| 队列 |
| 队列与堆栈 |
| 队列:先进先出 |
| 堆栈:先进后出 |
| |
2.deque
| from collections import deque |
| |
| d = deque([1,2,3]) |
| print(d.pop()) |
| print(d.popleft()) |
| |
3.defaultdict
| values = [11, 22, 33,44,55,66,77,88,99,90] |
| |
| my_dict = {} |
| |
| for value in values: |
| if value>66: |
| if my_dict.has_key('k1'): |
| my_dict['k1'].append(value) |
| else: |
| my_dict['k1'] = [value] |
| else: |
| if my_dict.has_key('k2'): |
| my_dict['k2'].append(value) |
| else: |
| my_dict['k2'] = [value] |
| |
| 原生字典解决方法 |
| |
| |
| from collections import defaultdict |
| |
| values = [11, 22, 33,44,55,66,77,88,99,90] |
| |
| my_dict = defaultdict(list) |
| |
| for value in values: |
| if value>66: |
| my_dict['k1'].append(value) |
| else: |
| my_dict['k2'].append(value) |
| |
| defaultdict字典解决方法 |
4.ordereddict顺序字典
| >>> from collections import OrderedDict |
| >>> d = dict([('a', 1), ('b', 2), ('c', 3)]) |
| >>> d |
| {'a': 1, 'c': 3, 'b': 2} |
| >>> od = OrderedDict([('a', 1), ('b', 2), ('c', 3)]) |
| >>> od |
| OrderedDict([('a', 1), ('b', 2), ('c', 3)]) |
| |
| |
| >>> od = OrderedDict() |
| >>> od['z'] = 1 |
| >>> od['y'] = 2 |
| >>> od['x'] = 3 |
| >>> od.keys() |
| ['z', 'y', 'x'] |
5.counter
| from collections import Counter |
| |
| c = Counter('asdhjgajksd') |
| print(c) |
常用内置模块时间模块
1.time

| import time |
| """ |
| 三种时间表现形式 |
| 1.时间戳 |
| 秒数 |
| 2.结构化时间 |
| 主要是给计算机看的 人看不适应 |
| 3.格式化时间 |
| 主要是给人看的 |
| """ |
| time.time() |
| |
| time.localtime() |
| ''' |
| time.struct_time(tm_year=2022, tm_mon=10, tm_mday=19, tm_hour=11, tm_min=32, tm_sec=50, tm_wday=2, tm_yday=292, tm_isdst=0) |
| ''' |
| |
| |
| time.strftime("%Y-%m-%d %H:%M:%S") |
| |
| time.strftime("%Y-%m-%d %X") |
| |
| time.sleep(1) |
| |
2.datetime

| from datetime import time,datetime,data |
| |
| print(datetime.now()) |
| print(datetime.today()) |
| print(datetime.utcnow()) |
| print(datetime.strftime()) |
| |
| |
| |
| ''' |
| datetime 年月日 时分秒 |
| date 年月日 |
| time 时分秒 |
| ''' |
| data.now() |
| |
| print(datetime.strptime('2022-10-19','%Y-%m-%d')) |
| print(datetime.strftime(datetime.today(),'%Y-%m-%d')) |
| |
| print(time.strptime('2022-10-19', '%Y-%m-%d')) |
| print(datetime.today()+timedelta(weeks=1)) |
| |
| |
| |
| datetime.timedelta(days = 3) |
| |
| |
| |
| date |
| |
| print(date.today()) |
| print(date.today().strftime('%Y-%m-%d')) |
| print(date.today().timetuple()) |
| |
| print(date.today().year) |
| |
| print(date.today().replace(2019)) |
| |
| print(date.today().ctime()) |
| print(date.today().toordinal()) |
| |
| print(date.today().weekday()) |
| |
| |
常用内置模块随机数模块
| random 模块 |
| import random |
| |
| random.random() |
| |
| random.randint(1,10) |
| |
| random.randrange(1,10,2) |
| |
| random.choice([1,2,3]) |
| |
| random.choices([1,2,3,4,5,6]) |
| |
| random.simple('akjsghd',2) |
| |
| l1= [1,2,3,4] |
| random.shuffle(l1) |
| |
| '''产生图片验证码: 每一位都可以是大写字母 小写字母 数字 4位''' |
| |
| import string |
| import random |
| |
| def get_code(num): |
| code = '' |
| for i in range(num): |
| data = string.ascii_lowercase + string.ascii_uppercase + string.digits |
| code += random.choice(data) |
| return code |
| |
| |
| print(get_code(10)) |
| |
| |
| |
| |
| |
string模块
| import string |
| |
| string.ascii_lowercase |
| string.ascii_uppercase |
| string.digits |
os模块(重要)
| import os |
| |
| |
| os.mkdir('d1') |
| os.makedirs('d1\d2\d3') |
| |
| |
| os.rmdir('di') |
| os.removedirs('d1\d2\d3') |
| |
| |
| os.listdir(r'c:\\') |
| os.walk(r'E:\pythonworkftp\16') |
| |
| |
| os.remove('tt2.py') |
| |
| |
| os.getcwd() |
| |
| |
| os.chdir(r'E:\pythonworkftp\16\d1\d2') |
| |
| |
| os.getlogin() |
| |
| |
| os.rename(r'E:\pythonworkftp\16\d1\a.py',r'E:\pythonworkftp\16\d1\d2\a.py') |
| |
| print(os.path.dirname(r'E:\pythonworkftp\16\d1\d2\a.py')) |
| |
| print(os.path.abspath(r'd1\d2\a.py')) |
| |
| print(os.path.exists(r'E:\pythonworkftp\16\d1\d2\a.py')) |
| |
| print(os.path.join(r"E:\pythonworkftp\16\d1\d2",'a')) |
| |
| print(os.path.isfile(r'E:\pythonworkftp\16\d1\d2\a.py')) |
| |
| print(os.path.sep) |
| |
| print(os.path.getsize(r'E:\pythonworkftp\16\d1\d2\a.py')) |
| |
| print(os.stat(r'E:\pythonworkftp\16\d1\d2\a.py').st_size) |
| |
| print(os.path.getmtime(r'E:\pythonworkftp\16\d1\d2\a.py')) |
| |
| |
sys模块
| import sys |
| |
| print(sys.path) |
| print(sys.version) |
| |
| |
| print(sys.getrecursionlimit()) |
| |
| print(sys.setrecursionlimit(2000)) |
| print(sys.getrecursionlimit()) |
| |
| print(sys.argv) |
| |
| print(sys.getwindowsversion()) |
json模块(重要)
| json模块也称为序列化模块 序列化可以打破语言限制实现不同编程语言之间数据交互 |
| |
| json格式数据作用 |
| |
| json格式数据的形式 |
| 字符串类型并且引号都是双引号 |
| |
| json相关操作 |
| 针对数据 |
| |
| json.dumps() |
| json.loads() |
| |
| 针对文件 |
| json.dump() |
| json.load() |
| |
| |
json模块补充
| import json |
| |
| d = {'name': 'jason老师', 'pwd': 123} |
| res = json.dumps(d) |
| print(res) |
| res = json.dumps(d, ensure_ascii=False) |
| print(res) |
json模块实战
| 用户登录注册功能 |
| import os |
| import json |
| |
| |
| |
| base_dir = os.path.dirname(__file__) |
| |
| db_dir = os.path.join(base_dir, 'db') |
| |
| if not os.path.isdir(db_dir): |
| os.mkdir(db_dir) |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| username = input('username>>>:').strip() |
| |
| target_user_file_path = os.path.join(db_dir, f'{username}.json') |
| if not os.path.isfile(target_user_file_path): |
| print('你赶紧滚蛋 用户名都不对 搞什么飞机') |
| else: |
| password = input('password>>>:').strip() |
| |
| with open(target_user_file_path,'r',encoding='utf8') as f: |
| real_user_dict = json.load(f) |
| if password == real_user_dict.get('password'): |
| print('登录成功') |
| else: |
| print('密码错误') |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步