1. 程式人生 > >python之路--內建常用模組

python之路--內建常用模組

1. 簡單的瞭解模組

  你寫的每一個py檔案都是一個模組. 還有一些我們一直在使用的模組.

  buildins  內建模組. print, input.

  random  主要是和隨機相關的的內容

    random() 隨機小數
    uninform(a,b) 隨機小數
    randint(a,b) 隨機整數
    choice() 隨機選擇一個
    sample() 隨機選擇多個
    shuffle() 打亂

import random
print(random.randint(10,20))

from random import randint
print(randint(10,20))

import random
print(random.randint(10,20)) # 隨機整數
print(random.random()) # python中所有隨機數的根 隨機小數 0-1
print(random.uniform(10,20)) # 10-20的隨機小數
lst = ["寶寶", "寶強", "寶浪", "包拯"]
random.shuffle(lst)  # 隨機打亂順序
print(lst)
# 從列表中隨機選擇一個
print(random.choice(["林志玲", "劉一菲", "王昭君", "艾米", "寶寶"]))
print(random.sample(["林志玲", "劉一菲", "王昭君", "艾米", "寶寶"], 3))

2.  Collections
  1. Counter 計數器

# from collections import Counter

# print(Counter("我我我你你他")) # 計數  Counter({'我': 3, '你': 2, '他': 1})
# lst = ["jay",'jay',"jay","寶寶","寶寶", "胡辣湯", "上官婉兒", "上官婉兒"]
# print(Counter(lst)) # Counter({'jay': 3, '寶寶': 2, '上官婉兒': 2, '胡辣湯': 1})

  2. defaultdict 預設值字典

from collections import defaultdict
# 預設值字典
dd = defaultdict(lambda: '武林盟主') # callable 可呼叫的, 字典是空的
dic = dd['張無忌']
print(dd)  # defaultdict(<function <lambda> at 0x0000007BEA451EA0>, {'張無忌': '武林盟主'})

  3. OrderedDict 有序字典

from collections import OrderedDict
# 有序字典
dic = OrderedDict()
dic["笑傲江湖"] = "令狐沖"
dic['天龍八部'] = "喬峰"
print(dic) # OrderedDict([('笑傲江湖', '令狐沖'), ('天龍八部', '喬峰')])
print(dic.get("笑傲江湖")) # 令狐沖
print(dic.values()) # odict_values(['令狐沖', '喬峰'])
print(dic['天龍八部']) # 喬峰

  資料結構(佇列, 棧(重點))

  棧:先進後出
    Stack

# 特點: 先進後出
class StackFullException(Exception):
    pass
class StackEmptyException(Exception):
    pass
class Stack:
    def __init__(self, size):
        self.size = size
        self.lst = [] # 存放資料的列表
        self.top = 0 # 棧頂指標
    # 入棧
    def push(self, el):
        if self.top >= self.size:
            raise StackFullException("your stack is full!!!!!")
        self.lst.insert(self.top, el) # 放元素
        self.top += 1 # 棧頂指標向上移動一下
    # 出棧
    def pop(self):
        if self.top == 0:
            raise StackEmptyException("your stack is empty!!!!!")
        self.top-=1
        el = self.lst[self.top]
        return el

s = Stack(4)
s.push("笑")
s.push("傲")
s.push("江")
s.push("湖")
print(s.pop()) # 湖
print(s.pop()) # 江
print(s.pop()) # 傲
print(s.pop()) # 笑

  

  佇列: 先進先出
    Queue

import queue
q = queue.Queue()
q.put("射")
q.put("雕")
q.put("英雄")
q.put("傳")

print(q.get()) # 射
print(q.get()) # 雕
print(q.get()) # 英雄
print(q.get()) # 傳

 

   雙向佇列

from collections import deque

d = deque() # 建立雙向佇列
d.append("書劍") #  在右側新增
d.append("恩仇")
d.append("錄")
d.appendleft("娃哈哈") # 在左邊新增
d.appendleft("爽歪歪")
d.appendleft("優酸乳")

print(d.pop()) # 從右邊拿資料   錄
print(d.pop()) # 從右邊拿資料  恩仇
print(d.pop()) # 從右邊拿資料  書劍
print(d.popleft()) # 從左邊拿資料  優酸乳
print(d.popleft()) # 從左邊拿資料  爽歪歪
print(d.popleft()) # 從左邊拿資料  娃哈哈

  

3. Time模組
  時間有三種:
  結構化時間 gmtime() localtime()
  時間戳 time.time() time.mktime()
  格式化時間 time.strftime() time.strptime()

import time

# 時間戳: 從1970-01-01 00:00:00開始計算. 未來儲存的時候用是時間戳
print(time.time())  # 顯示的是從1970-01-01 00:00:00開始計算到現在是多少秒

# 格式化時間
print(time.strftime("%Y-%m-%d %H:%M:%S"))  # 用來顯示的  # 2018-12-26 12:38:56

# 結構化時間(python的時間)
print(time.localtime()) 
t = time.localtime()
print(t.tm_year)  # 2018
print(t.tm_mon)   # 12
print(t.tm_mday)  # 26

  時間轉化:
  數字 -> 字串
  struct_time = time.localtime(數字)
  str = time.strftime("格式", struct_time)

import time
 # 資料庫中儲存一個數字,把它還原成我們的格式化時間
a = 1541952464
# 先把這個時間戳轉化成python中的結構化時間
t = time.localtime(a)  # 東八區時間
# 把這個結構化時間轉化成格式化時間
s = time.strftime('%Y-%m-%d %H:%M:%S', t)
print(s) # 2018-11-12 00:07:44

  

# 資料庫裡儲存一個數字. 把它還原成我們的格式化時間
a = 0  # 可以在範圍內隨便設
# 先把這個時間戳轉化成python中的結構化時間
t = time.gmtime(a) # 格林尼治時間
# 把一個結構化時間轉化成格式化時間
s = time.strftime("%Y-%m-%d %H:%M:%S", t)
print(s)  # 1970-01-01 00:00:00

  

  字串 -> 數字
  struct_time = time.strptime(字串, "格式")
  num = time.mktime(struct_time)

  無論是由時間戳轉化成格式化時間 還是由 格式化時間轉化成時間戳都需要經過結構化時間

# 使用者輸入一個時間,然後把時間轉化成時間戳
strf = input('請輸入一個時間:')  # 2018-12-12 21:12:43
# 把字串轉化成結構化時間
t = time.strptime(strf,'%Y-%m-%d %H:%M:%S')
print(time.mktime(t)) # 1544620363.0

 

4. functools
  wraps 給裝飾器中的inner改名字

from functools import wraps # 可以改變一個函式的名字, 註釋...

def wrapper(fn):
    @wraps(fn)  # 把inner的名字改變成原來的func
    def inner(*args, **kwargs):
        print("前")
        ret = fn(*args, **kwargs)
        print("後")
        return ret
    return inner
@wrapper # func = wrapper(func)
def func():
    print('哈哈哈')
print(func.__name__) # func  如果沒有@wraps 列印的就是inner

  

  reduce 歸納.

from functools import reduce
def func(a, b):
    return a + b # 0+1+2+3+4+5+6# 累加

# 會把我們每一個數據交給func去執行, 把預設值作為第一個引數傳遞給函式
# 第二個引數就是你這個序列中的第一個資料
# 接下來. 把剛才返回的結果作為第一個引數傳遞個a
# 繼續吧剛才的結果給第一個引數. 把第三個資料傳遞給b
ret = reduce(func, [1,2,3,4,5,6])
# 工作流程
# func(func(func(0, 1),2),4)
print(ret)
print(reduce(lambda x, y:x + y, [i for i in range(101)])) # 5050

 

  偏函式 把函式的引數固定.

from functools import partial

def eat(zhushi, fushi):
    print(zhushi, fushi)
# 固定函式中某些引數的值
eat2 = partial(eat, fushi="辣雞爪")
eat2("大米飯") # 大米飯 辣雞爪
eat2("小米飯") # 小米飯 辣雞爪
eat2("黑米飯") # 黑米飯 辣雞爪