一、collection子產品
1.nametuple(具名元組)
生成可以使用名字來通路元素内容的tuple
2.例子:
(1)表示坐标
from collections import namedtuple
point = namedtuple('坐标',['x','y','z']) # 第二個參數既可以傳可疊代對象
point = namedtuple('坐标','x y z') # 也可以傳字元串 但是字元串之間以空格隔開
p = point(1,2,5) # 注意元素的個數必須跟namedtuple第二個參數裡面的值數量一緻
print(p)
print(p.x)
print(p.y)
print(p.z)
注意:nametuple第二個參數既可以傳可疊代對象,也可以傳字元串,字元串之間以空格隔開
元素的個數必須跟nametuple第二個參數裡面的值數量一緻
(2)撲克牌
from collections import namedtuple
card = namedtuple('撲克牌','color number')
# card1 = namedtuple('撲克牌',['color','number'])
A = card('♠','A') # 撲克牌(color='♠', number='A')
print(A)
print(A.color)
print(A.number)
2.deque:是為了高效實作插入和删除操作的雙向清單,适用于隊列和棧
隊列:先進先出(FIFO first in first out)
import queue
q = queue.Queue() # 生成隊列對象
q.put('first') # 往隊列中添加值
q.put('second')
q.put('third')
print(q.get()) # 朝隊列要值
print(q.get())
print(q.get())
print(q.get()) # 如果隊列中的值取完了 程式會在原地等待 直到從隊列中拿到值才停止
deque雙端隊列除了實作list的append()和pop()外,還支援appendleft()和popleft(),這樣就可以非常高效地往頭部添加或删除元素
from collections import deque
q = deque(['a','b','c'])
q.append(1)
q.appendleft(2)
q.insert(0,'哈哈哈') # 特殊點:雙端隊列可以根據索引在任意位置插值
print(q.pop()) # 1
print(q.popleft()) # 哈哈哈
print(q.popleft()) # 2
注意:隊列不應該支援任意位置插值,隻能在首尾插值(不能插隊)
雙端隊列可以根據索引在任意位置插值
3.OrderedDict:有序字典
from collections import OrderedDict
d = dict([('a', 1), ('b', 2), ('c', 3)])
print(d) # dict的Key是無序的 {'a': 1, 'c': 3, 'b': 2}
od = OrderedDict([('a', 1), ('b', 2), ('c', 3)])
print(od) # OrderedDict的Key是有序的 OrderedDict([('a', 1), ('b', 2), ('c', 3)])
注意:OrderedDict的Key會按照插入的順序排列,不是Key本身排序:
from collections import OrderedDict
od = OrderedDict()
od['z'] = 1
od['y'] = 2
od['x'] = 3
print(od.keys()) # 按照插入的Key的順序傳回 ['z', 'y', 'x']
4.defaultdict:帶有預設值的字典
from collections import defaultdict
values = [11, 22, 33,44,55,66,77,88,99,90]
my_dict = defaultdict(list) # 後續該字典中建立的key對應的value預設就是清單
print(my_dict['aaa']) # []
for value in values:
if value>66:
my_dict['k1'].append(value)
else:
my_dict['k2'].append(value)
print(my_dict)
# defaultdict(<class 'list'>, {'aaa': [], 'k2': [11, 22, 33, 44, 55, 66], 'k1': [77, 88, 99, 90]})
from collections import defaultdict
my_dict1 = defaultdict(int) # 後續該字典中建立的key對應的value預設就是整型
print(my_dict1['xxx']) # 0
my_dict2 = defaultdict(bool) # 後續該字典中建立的key對應的value預設就是布爾值
print(my_dict2['kkk']) # False
my_dict3 = defaultdict(tuple) # 後續該字典中建立的key對應的value預設就是元組
print(my_dict3['mmm']) # ()
5.counter:計數器,用來跟蹤值出現的次數。它是一個無序的容器類型,以字典的鍵值對形式存儲,其中元素作為key,其計數作為value。
from collections import Counter
s = 'abcdeabcdabcaba'
res = Counter(s)
print(res) # Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1})
二、time與datetime子產品
1.表示時間的三種方式
(1)時間戳:時間戳表示的是從1970年1月1日00:00:00開始按秒計算的偏移量。我們運作“type(time.time())”,傳回的是float類型。計算機能夠識别的時間
(2)格式化時間(用來展示給人看的):‘1999-12-06’
python中時間日期格式化符号
(3)結構化時間:操作時間的
2.時間字元串
import time
print(time.strftime('%Y-%m-%d')) # 2019-07-18
print(time.strftime('%Y-%m-%d %H:%M:%S')) # 2019-07-18 18:47:04
print(time.strftime('%Y-%m-%d %X')) # %X等價于%H:%M:%S
print(time.strftime('%H:%M')) # 18:47
print(time.strftime('%Y/%m')) # 2019/07
3.時間元組:localtime将一個時間戳轉換為目前時區的struct_time
import time
print(time.localtime()) # time.struct_time(tm_year=2019, tm_mon=7, tm_mday=18, tm_hour=18, tm_min=55, tm_sec=26, tm_wday=3, tm_yday=199, tm_isdst=0)
print(time.strftime('%Y-%m',time.localtime())) # 2019-07
4.結構化時間--時間戳(mktime)
import time
time_tuple = time.localtime(1500000000)
res = time.mktime(time_tuple)
print(res) # 1500000000.0
5.結構化時間--字元串時間(strftime)
import time
res = time.strftime("%Y-%m-%d %X")
print(res) # 2019-07-18 19:03:39
res1 = time.strftime("%Y-%m-%d",time.localtime(1563447870.4117234))
print(res1) # 2019-07-18
6.字元串時間--結構化時間(strptime)
import time
print(time.strptime(time.strftime('%Y-%m',time.localtime()),'%Y-%m'))
# time.struct_time(tm_year=2019, tm_mon=7, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=182, tm_isdst=-1)
7.擷取年月日
import datetime
now_date = datetime.date.today()
print(now_date) # 2019-07-18
8.擷取年月日時分秒
import datetime
now_time = datetime.datetime.today()
print(now_time) # 2019-07-18 19:10:21.040734
import datetime
res = datetime.datetime.today()
print(res.year) # 擷取年份
print(res.month) # 擷取月份
print(res.day) # 擷取日期
print(res.weekday()) # 0-6表示星期 0表示周一
print(res.isoweekday()) # 1-7表示星期 7就是周日
9.日期對象 = 日期對象 +/- timedelta對象
timedelta對象 = 日期對象 +/- 日期對象
import datetime
current_time = datetime.date.today() # 日期對象
timetel_t = datetime.timedelta(days=7) # timedelta對象
res1 = current_time+timetel_t # 日期對象
print(current_time - timetel_t) # 2019-07-11
print(res1-current_time) # 7 days, 0:00:00
例子:計算今天距離今年過生日還有多少天
import datetime
birth = datetime.datetime(2020,1,17,8,8,8)
current_time = datetime.datetime.today()
print(birth-current_time)
UTC時間(總結年月日時分秒及時區問題)
import datetime
dt_today = datetime.datetime.today()
dt_now = datetime.datetime.now()
dt_utcnow = datetime.datetime.utcnow()
print(dt_utcnow,dt_now,dt_today)
# 2019-07-18 11:20:25.553920 2019-07-18 19:20:25.553920 2019-07-18 19:20:25.553921
三、random子產品
1.随機小數
import random
res = random.random() # 大于0且小于1之間的小數
2.随機整數
import random
random.randint(1,5) # 大于等于1且小于等于5之間的整數
3.随機選擇一個傳回
import random
random.choice([1,'23',[4,5]]) # #1或者23或者[4,5]
4.打亂清單順序(洗牌)
import random
res = [1,2,3,4,5,6]
random.shuffle(res) # 洗牌
5.生成随機驗證碼
"""
大寫字母 小寫字母 數字
5位數的随機驗證碼
chr
random.choice
封裝成一個函數,使用者想生成幾位就生成幾位
"""
def get_code(n):
code = ''
for i in range(n):
# 先生成随機的大寫字母 小寫字母 數字
upper_str = chr(random.randint(65,90))
lower_str = chr(random.randint(97,122))
random_int = str(random.randint(0,9))
# 從上面三個中随機選擇一個作為随機驗證碼的某一位
code += random.choice([upper_str,lower_str,random_int])
return code
res = get_code(4)
print(res)
四、os子產品
1.os子產品:跟作業系統打交道的子產品
2.需要掌握的方法:
(1)os.path.dirname(path):傳回path的目錄。
(2)os.path.join(path1[,path2[,...]]):将多個路徑組合後傳回,第一個絕對路徑之前的參數将被忽略
(3)os.listdir('dirname'):列出指定目錄下的所有檔案和子目錄,包括隐藏檔案,并以清單方式列印
(4)os.mkdir('dirname'):生成單級目錄
(5)os.path.exists(path):如果path存在,傳回True;如果path不存在,傳回False
(6)os.path.isfile(path):如果path是一個存在的檔案,傳回True。否則傳回False
(7)os.rmdir('dirname'):删除單級空目錄,若目錄不為空則無法删除,報錯
(8)os.getcwd():擷取目前工作目錄,即目前python腳本工作的目錄路徑
(9)os.chdir("dirname"):改變目前腳本工作目錄
(10)os.path.getsize(path):傳回path的大小(位元組大小和字元大小)
3.了解部分
os.makedirs('dirname1/dirname2') 可生成多層遞歸目錄
os.removedirs('dirname1') 若目錄為空,則删除,并遞歸到上一級目錄,如若也為空,則删除,依此類推
os.remove() 删除一個檔案
os.rename("oldname","newname") 重命名檔案/目錄
os.stat('path/filename') 擷取檔案/目錄資訊
os.system("bash command") 運作shell指令,直接顯示
os.popen("bash command).read() 運作shell指令,擷取執行結果
os.path.abspath(path) 傳回path規範化的絕對路徑
os.path.split(path) 将path分割成目錄和檔案名二進制組傳回
os.path.basename(path) 傳回path最後的檔案名。如何path以/或\結尾,那麼就會傳回空值。即os.path.split(path)的第二個元素
os.path.isabs(path) 如果path是絕對路徑,傳回True
os.path.isdir(path) 如果path是一個存在的目錄,則傳回True。否則傳回False
os.path.getatime(path) 傳回path所指向的檔案或者目錄的最後通路時間
os.path.getmtime(path) 傳回path所指向的檔案或者目錄的最後修改時間
五、sys子產品
1.sys子產品是與python解釋器互動的一個接口
2.常用方法:
(1)sys.argv:指令行啟動檔案 可以做身份的驗證
(2)sys.path:傳回子產品的搜尋路徑,初始化時使用PYTHONPATH環境變量的值
(3)sys.exit(n):退出程式,正常退出時exit(0),錯誤退出sys.exit(1)
(4)sys.version:擷取Python解釋程式的版本資訊
(5)sys.platform:傳回作業系統平台名稱
3.例子:使用者身份驗證
import sys
print(sys.argv) # 指令行啟動檔案 可以做身份的驗證
if len(sys.argv) <= 1:
print('請輸入使用者名和密碼')
else:
username = sys.argv[1]
password = sys.argv[2]
if username == 'jason' and password == '123':
print('歡迎使用')
# 目前這個py檔案邏輯代碼
else:
print('使用者不存在 無法執行目前檔案')
六、序列化子產品
1.序列化:其他資料類型轉換成字元串的過程
2.反序列化:字元串轉成其他資料類型
3.寫入檔案的資料必須是字元串,基于網絡傳輸的資料必須是二進制
4.json子產品:
所有的語言都支援json格式
支援的資料類型很少,如字元串、清單、字典、整型、元組(轉成清單)布爾值
dumps和loads
import json
d = {"name":"jason"}
print(d) # {'name': 'jason'}
res = json.dumps(d) # json格式是字元串 必須是雙引号 >>>: '{"name": "jason"}'
print(res,type(res)) # {"name": "jason"} <class 'str'>
res1 = json.loads(res)
print(res1,type(res1)) # {'name': 'jason'} <class 'dict'>
dump和load
import json
d = {"name":"jason"}
with open('userinfo','w',encoding='utf-8') as f:
json.dump(d,f) # dump方法接收一個檔案句柄,直接将字典轉換成json字元串寫入檔案
with open('userinfo','r',encoding='utf-8') as f:
res = json.load(f) # load方法接收一個檔案句柄,直接将檔案中的json字元串轉換成資料結構傳回
import json
d = {"name":"jason"}
with open('userinfo','w',encoding='utf-8') as f:
json_str = json.dumps(d)
json_str1 = json.dumps(d)
f.write('%s\n'%json_str)
f.write('%s\n'%json_str1)
with open('userinfo','r',encoding='utf-8') as f:
for line in f:
res = json.loads(line)
print(res,type(res))
# {'name': 'jason'} <class 'dict'>
# {'name': 'jason'} <class 'dict'>
t = (1,2,3,4)
print(json.dumps(t)) # [1, 2, 3, 4]
ensure_ascii關鍵字參數
import json
d1 = {'name':'豬堅強'}
print(json.dumps(d1,ensure_ascii=False)) # {"name": "豬堅強"}
5.pickel子產品:
隻支援python
python所有的資料類型都支援
import pickle
d = {'name':'jason'}
res = pickle.dumps(d) # 将對象直接轉成二進制
print(res)
res1 = pickle.loads(res)
print(res1,type(res1)) # {'name': 'jason'} <class 'dict'>
用pickle操作檔案的時候,檔案的打開模式必須是b模式
七、subprocess子產品
sub:子,process:程序
"""
1.使用者通過網絡連接配接上了你的這台電腦
2.使用者輸入相應的指令 基于網絡發送給了你這台電腦上某個程式
3.擷取使用者指令 裡面subprocess執行該使用者指令
4.将執行結果再基于網絡發送給使用者
這樣就實作 使用者遠端操作你這台電腦的操作
"""
while True:
cmd = input('cmd>>>:').strip()
import subprocess
obj = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
# print(obj)
print('正确指令傳回的結果stdout',obj.stdout.read().decode('gbk'))
print('錯誤指令傳回的提示資訊stderr',obj.stderr.read().decode('gbk'))
轉載于:https://www.cnblogs.com/yljbky/articles/11209790.html