Python——collections模塊、time模塊、random模塊、os模塊、sys模塊

1. collections模塊

(1)namedtuple

# (1)點的座標
from collections import namedtuple
Point = namedtuple('point',['x','y'])

# 前兩行能夠用下面兩行代替
# import collections
# Point = collections.namedtuple('point',['x','y'])
p = Point(1,2)
print(p.x)  #1
print(p.y)  #2
print(p)    #point(x=1, y=2)
View Code

撲克牌的花色和數字html

from collections import namedtuple
Card = namedtuple('card',['suits','number'])
c1 = Card('紅桃',2)
print(c1.suits)     #紅桃
print(c1.number)    #2
print(c1)     #card(suits='紅桃', number=2)
View Code

(2)queue 隊列——FIFO 先進先出

import queue

q = queue.Queue()
q.put(10)
q.put(5)
q.put(8)
print(q.qsize())    #3
print(q)    #<queue.Queue object at 0x00000144985010B8>
print(q.get())  #10
print(q.get())  #5
print(q.get())  #8
print(q.get())  #阻塞:取完值以後繼續取,不會報錯
View Code

(3)deque——雙端隊列

from collections import deque
dq = deque([5,6])
dq.appendleft('a')  #從前面放數據   ['a',5,6]
dq.append('b')      #從後面放數據   ['a',5,6,'b']
dq.insert(0,3)      # [3,'a',5,6,'b']
print(dq)   #deque([3, 'a', 5, 6, 'b'])
print(dq.popleft())     #從前面取數據:3
print(dq.popleft())     #從前面取數據:a
print(dq.pop())         #從後面取數據:b
print(dq.pop())         #從後面取數據:6
print(dq)   #deque([5])
View Code

(4)OrderedDict 有序字典

  字典取值快,可是存儲時比列表佔內存多python

from collections import  OrderedDict
od = dict([('a',1),('b',2),('c',3)])
print(od)   #有序:{'a': 1, 'b': 2, 'c': 3}
print(od['a'])  #1
for k in od:
    print(k)    # a    b   c
View Code

(5)defaultdict——默認字典

  key不存在時,返回一個默認值linux

  舉例:將大於66的數放在k1,小於66的數放在k2面試

from collections import defaultdict
values = [11,22,33,44,55,66,77,88,99,100]
my_dict = defaultdict(list)  #默認list
for value in values:
    if value>66:
        my_dict['k1'].append(value)
    else:
        my_dict['k2'].append(value)
print(my_dict['k1'])    #[77, 88, 99, 100]
print(my_dict['k2'])    #[11, 22, 33, 44, 55, 66]
View Code

  defaultdict的用法shell

from collections import defaultdict
d = defaultdict(list)
print(d['k'])   #[]

from collections import defaultdict
d1 = defaultdict(dict)
print(d1['k'])   #{}

from collections import defaultdict
dd = defaultdict(lambda:'默認值')
dd['key1'] = 'abc'
print(dd['key1'])   #key1存在,返回:abc
print(dd['key2'])   #key2不存在,返回:默認值(能夠隨意設置)
View Code

(6)Counter——跟蹤值出現的次數

from collections import Counter
c = Counter('abacadfdcbcdf')
print(c)    #Counter({'a': 3, 'c': 3, 'd': 3, 'b': 2, 'f': 2})
View Code

2. time模塊

(1)時間戳時間(timestamp)——float時間:給計算機看的

(2)格式化時間(Format String)——字符串:給人看的

#格式化時間:時間字符串strftime

print(time.strftime('%Y-%m-%d %a %H:%M:%S' ))     # 2018-10-08 Mon 15:04:01 Year month day week Hour Minute Seconds
print(time.strftime('%Y/%m/%d %H:%M:%S' ))     # 2018/10/08 15:05:23  Year month day Hour Minute Seconds
print(time.strftime('%m-%d %H:%M:%S' ))     # 10-08 15:04:01  month day Hour Minute Seconds
print(time.strftime('%H:%M:%S' ))     # 15:04:01  Hour Minute Seconds
print(time.strftime('%H:%M' ))     # 15:04  Hour Minute
View Code

(3)結構化時間(struct_time)——元祖:計算用的

#結構化時間

#localtime
struct_time = time.localtime()
print(struct_time)  #time.struct_time(tm_year=2018, tm_mon=10, tm_mday=8, tm_hour=15, tm_min=7, tm_sec=53, tm_wday=0, tm_yday=281, tm_isdst=0)
print(struct_time.tm_year)  #2018

#gmtime
struct_time1 = time.gmtime()
print(struct_time1)  #time.struct_time(tm_year=2018, tm_mon=10, tm_mday=8, tm_hour=15, tm_min=7, tm_sec=53, tm_wday=0, tm_yday=281, tm_isdst=0)
print(struct_time1.tm_year)  #2018
View Code

(4)三者的相互轉換

(5)相互轉換代碼

t = time.time()
print(t)    #1538982828.2859974
print(time.localtime(t))    #time.struct_time(tm_year=2018, tm_mon=10, tm_mday=8, tm_hour=15, tm_min=13, tm_sec=3, tm_wday=0, tm_yday=281, tm_isdst=0)
print(time.gmtime(t))       #time.struct_time(tm_year=2018, tm_mon=10, tm_mday=8, tm_hour=7, tm_min=13, tm_sec=3, tm_wday=0, tm_yday=281, tm_isdst=0)
print(time.localtime(1500000000))    #time.struct_time(tm_year=2017, tm_mon=7, tm_mday=14, tm_hour=10, tm_min=40, tm_sec=0, tm_wday=4, tm_yday=195, tm_isdst=0)

print(time.mktime(time.localtime()))    #1538982958.0

t = time.strptime('2000-12.31','%Y-%m.%d')
print(t)    #time.struct_time(tm_year=2000, tm_mon=12, tm_mday=31, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=366, tm_isdst=-1)
print(time.strftime('%m/%d/%y %H:%M:%S',time.localtime(3000000000)))    #01/24/65 13:20:00

print(time.asctime())   # Mon Oct  8 15:21:02 2018
print(time.asctime(time.localtime()))   # Mon Oct  8 15:21:02 2018
print(time.asctime(time.localtime(2000000000)))   # Wed May 18 11:33:20 2033
print(time.ctime())     # Mon Oct  8 15:21:02 2018
print(time.ctime(2000000000))   # Wed May 18 11:33:20 2033
View Code

3. random模塊

(1)隨機小數

import random

print(random.random())  # (0,1)之間的任意一個小數
print(random.uniform(1,3))  # (1,3)之間的任意一個小數
View Code

(2)隨機整數

import random

print(random.randint(1,5))         # [1,5]之間的任意一個整數
print(random.randrange(1,5))       # [1,4]之間的任意一個整數
print(random.randrange(1,10,2))    # [1,9]之間的任意一個整數奇數
View Code

(3)選擇一個返回

import random

print(random.choice([1,'23',[4,5]]))    # 隨機選擇一個返回:列表任意一個元素
View Code

(4)選擇多個返回

import random

print(random.sample([1,'23',[4,5],5,4,9],3))  # 隨機選擇多個返回:返回個數是函數的第二個參數
View Code

(5)打亂列表序列

import random

item = [1,3,5,7,9]
print(item)     # [1, 3, 5, 7, 9]
random.shuffle(item)
print(item)     # [5, 9, 3, 7, 1]
View Code

(6)驗證碼的生成

  詳見:筆試面試題  https://www.cnblogs.com/xc-718/p/9632731.htmlwindows

4. sys模塊

import sys

sys.exit()  # 退出程序:exit(1) 錯誤退出,exit(0) 正常退出
print(sys.platform) # win32【不許】
# 獲取Python解釋程序的版本信息
print(sys.version)  # 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)]

# 返回模塊的搜索路徑
print(sys.path)     # 全部路徑
print(sys.path.clear())     # 清空以後,import sys 會報錯
View Code

sys.argvapp

import sys

print(sys.argv)     # ['E:/Python/day19/06 sys.py']

ret = sys.argv
name = ret[1]
pwd = ret[2]
if name == 'xc' and pwd == '1234':
    print('登錄成功')
else:
    print('錯誤的用戶名或密碼')
    sys.exit()
print('你能夠使用本系統了')
View Code

5.os模塊

(1)os.getcwd()

import os

print(os.getcwd())  #獲取當前工做目錄: E:\Python\day19
os.chdir(r'E:\Python')  #改變當前腳本的工做目錄,通常不會用到
print(os.getcwd())  #獲取當前工做目錄: E:\Python
os.chdir(r'E:\Python\day19')  #改變回本來的工做目錄
print(os.getcwd())  #獲取當前工做目錄: E:\Python\day19
View Code

 

import sys

print(sys.argv)     # ['E:/Python/day19/06 sys.py']

ret = sys.argv
name = ret[1]
pwd = ret[2]
if name == 'xc' and pwd == '1234':
    print('登錄成功')
else:
    print('錯誤的用戶名或密碼')
    sys.exit()
print('你能夠使用本系統了')
View Code

(2)文件和目錄操做

import os

print(os.getcwd())  #E:\Python\day19
os.chdir('..')  #改變目錄到當前目錄的父目錄
print(os.getcwd())  #E:\Python


print(os.curdir)    # .     當前目錄
print(os.pardir)    # ..    當前目錄的父目錄,也就是上一層目錄


os.makedirs('dir1/dir2')    #建立多層目錄
os.removedirs('dir1/dir2')  #遞歸刪除,一直刪到上層目錄不爲空爲止
os.mkdir('dir1')    #建立單級目錄
os.rmdir('dir1')     #刪除單極空目錄,不爲空不刪除


print(os.listdir(r'E:\Python\day19'))   #列出指定目錄下全部的文件和子目錄,包含隱藏文件,並以列表方式打印


os.rename('06.sys.py','06 sys.py')      # 重命名文件
os.remove('E:/Python/day19/07 delete')      # 刪除一個文件


print(os.stat('E:/Python/day19/06 做業.py'))  # 獲取文件/目錄信息
View Code

(3)代碼跨平臺

import os

# python 代碼跨平臺
print(os.sep)
# 輸出操做系統特定的路徑分隔符
    # windows  \        E:\Python\day19
    # linux    /        E:/Python/day19
print(os.pathsep)
# 輸出用於分割文件路徑的字符串
    # windows  ;        E:\Python\day19;E:\Python\day19;E:\Python\day19
    # linux    :        E:\Python\day19:E:\Python\day19:E:\Python\day19
print(os.name)
# 輸出字符串指示當前平臺
    # windows  nt
    # linux    posix
View Code

(4)與路經有關

import os

# 與路徑有關的
print(os.path)  #絕對路徑 <module 'ntpath' from 'D:\\download\\Python\\lib\\ntpath.py'>
# 返回path規範化的絕對路徑
print(os.path.abspath(os.getcwd()))  #E:\Python\day19

print(os.getcwd())  # 獲取當前路徑 E:\Python\day19
# 用split將路徑分割成:(目錄,文件名)
print(os.path.split(os.getcwd()))   #('E:\\Python', 'day19')

# 返回path的目錄
print(os.path.split(os.getcwd()))   #('E:\\Python', 'day19')
print(os.path.dirname(os.getcwd()))  # E:\Python
print(os.path.basename(os.getcwd()))   # day19

print(os.path.exists())     # path存在,返回True;不存在,返回False
print(os.path.isabs())      # path是絕對路徑,返回True
print(os.path.isfile())     # path是一個存在的文件,返回True
print(os.path.isdir())      # path 是一個存在的目錄,返回True
print(os.path.join('c:','user','local'))       # c:user\local 多個路徑組合後返回,第一個絕對路徑以前的參數被忽略
print(os.path.getatime())   # 返回path所指向的文件/目錄的最後訪問時間
print(os.path.getmtime())   # 返回path所指向的文件/目錄的最後修改時間

# 返回path的大小
print(os.path.getsize(os.getcwd()))    # 4096【文件夾最大這麼大】
print(os.path.getsize(os.path.join(os.getcwd(),'03 time.py')))    # 2546【文件大小】
View Code

(5)其餘

import os

os.system('dir')   # 運行shell命令,直接顯示,無返回值不能直接操做
print(os.popen('dir').read())   # 運行shell命令,獲取執行結果,有返回值

# 獲取系統的環境變量
print(os.environ)   
View Code
相關文章
相關標籤/搜索