日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

推荐几个实用的Python“小伎俩”

發布時間:2025/3/8 python 18 豆豆
生活随笔 收集整理的這篇文章主要介紹了 推荐几个实用的Python“小伎俩” 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

寫在前面

今天一起回顧下Python Cookbook,全書是以問答對的形式展開,這是我很久之前看的筆記。Cookbook不算是入門書,更像是一本工具書,既然有基礎了那就沒必要一個個點去看,建議是需要用到那部分就把那塊的知識點技巧翻一遍。下面大噶自己查漏補缺吧!

Chap1 數據結構與算法

從任意長度的可迭代對象中分解元素

*表達式可以用來將一個含有N個元素的數據結構類型分解成所需的幾部分。
例如grades保存了100個成績數據而我們只關心首末兩個成績,就可以把中間的所有成績保存到一個列表里面,如下:

first, *middle, last = grades
保存最后N個元素
  • collection.deque(maxlen=N)創建了一個固定長度的隊列,當有新記錄加入而隊列已滿時會自動移除最老的那條記錄。

  • 若不指定隊列的大小,也就得到了一個無界限的隊列;

  • deque支持從隊列兩端添加或彈出元素

from collection import deque q = deque() q.append(1) q.append(2) q.append(3) q.appendleft(4) q.pop() q.popleft()
找到最大或最小的N個元素
  • heapq模塊中有兩個函數:nlargest()和nsmallest()

import heapqnums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2] print(heapq.nlargest(3, nums)) out: [42, 37, 23] print(heapq.nsmallest(3,nums)) out: [-4, 1, 2]
  • 這兩個函數還可以接受一個參數key

In [1]: portfolio = [...: {'name': 'IBM', 'shares': 100, 'price': 91.1},...: {'name': 'AAPL', 'shares': 50, 'price': 543.22},...: {'name': 'FB', 'shares': 200, 'price': 21.09},...: {'name': 'HPQ', 'shares': 35, 'price': 31.75},...: {'name': 'YHOO', 'shares': 45, 'price': 16.35},...: {'name': 'ACME', 'shares': 75, 'price': 115.65}...: ]cheap = heapq.nsmallest(3, portfolio, key=lambda s: s['price']) cheap out: [{'name': 'YHOO', 'price': 16.35, 'shares': 45},{'name': 'FB', 'price': 21.09, 'shares': 200},{'name': 'HPQ', 'price': 31.75, 'shares': 35}]

讓字典保持有序

  • collection模塊的OrderedDict會按照元素初始添加的順序進行操作;

  • 其內部維護了一個雙向鏈表,它會根據元素加入的順序來排列鍵的位置。因此OrderedDict的大小是普通字典的2倍多。

字典的計算問題

  • 利用zip()將字典的鍵與值反轉

找出序列中出現次數最多的元素

  • collection模塊的Counter類

  • 并且Counter類有一個非常方便的most_common(n)方法可以直接得到出現次數最多的前幾位

from collections import Counter words = [一系列單詞組成的列表] word_counts = Counter(words) top_3 = word_counts.most_common(3)

通過公共鍵對字典列表排序

  • operator模塊的itermgetter函數

from operator import itemgetterIn [26]: rows = [...: {'fname': 'Brian', 'lname': 'Jones', 'uid':1003},...: {'fname': 'David', 'lname': 'Beazley', 'uid':1002},...: {'fname': 'John', 'lname': 'Cleese', 'uid':1001},...: {'fname': 'Big', 'lname': 'Jones', 'uid':1004}...: ]itemgetter('fname') Out[31]: <operator.itemgetter at 0x7f01606657d0>rows_by_frame = sorted(rows, key=itemgetter('fname')) Out[30]: [{'fname': 'Big', 'lname': 'Jones', 'uid': 1004},{'fname': 'Brian', 'lname': 'Jones', 'uid': 1003},{'fname': 'David', 'lname': 'Beazley', 'uid': 1002},{'fname': 'John', 'lname': 'Cleese', 'uid': 1001}]
  • itermgetter()函數還可以接受多個鍵

rows_by_frame = sorted(rows, key=itemgetter('fname','lname'))

Chap3 數字、日期和時間

對數值進行取整

  • 使用內建的round(value, ndigits)函數

>>> round(1.23, 1) 1.2 >>> round(1.27, 1) 1.3 >>> round(162773, -1) 162770
  • 當某個值恰好等于兩個整數間的一半時,取整操作會去到離該值最近的那個偶數上。如1.5和2.5都會取整到2

  • round()中的ndigits可以是負數,在這種情況下會相應地取整到十位、百位。。。

對數值做格式化輸出

  • 使用內建的format()函數

>>>x = 123.456 >>>format(x, '0.2f') 123.46

二進制、八進制和十六進制轉換

  • 要將一個整數轉換為二進制,使用bin()

  • 要將一個整數轉換為八進制,使用oct()

  • 要將一個整數轉換為十六進制,使用hex()

隨機選擇

  • random.choice()可以從序列中隨機挑選出元素

>>>import random >>>values = [1,2,3,4,5,6] >>>random.choice(values) 4 >>>random.choice(values) 2
  • random.shuffle()可以在序列中原地打亂元素的順序

>>>random.shuffle(values) >>>values [2,4,3,1,6,5]
  • random.sample()可以取樣出N個元素

>>>random.sample(values, 2) [6, 2]

時間換算

  • datatime模塊可以用來完成不同時間單位間的換算。例如要表示一個時間間隔,可以創建一個timedelta實例

from datetime import timedeltaIn [33]: a = timedelta(days=2, hours=6) In [34]: b = timedelta(hours=4.5) In [35]: c = a + b In [36]: c.days Out[36]: 2 In [37]: c.seconds Out[37]: 37800 In [38]: c.seconds/3600 Out[38]: 10.5 In [39]: c.total_seconds() / 3600 Out[39]: 58.5

Chap4 迭代器和生成器

手動訪問迭代器中的元素

with open('/etc/passwd') as f:try:while True:line = next(f)print(line, end='')except StopIteration:pass

委托迭代

  • 對自定義的容器對象,其內部持有一個列表丶元組或其他的可迭代對象,我們想讓自己的新容器能夠完成迭代操作。一般來說,我們所要做的就是定義一個__iter__()方法,將迭代請求委托到對象內部持有的容器上。

class Node:def __init__(self, value):Self._value = vauleself._children = []def __repr__(self):return 'Node({!r})'.format(self._value)def __iter__(self):return iter(self._children)

在這個例子中,iter()方法將迭代請求轉發給對象內部持有的_children屬性上。

用生成器創建新的迭代模式

  • 函數中只要出現了yield語句就會將其轉變成一個生成器

def frange(start, stop, increment):x = startwhile x < stop:yield xx += increment
  • 注意生成器只在響應迭代操作時才運行

對迭代器做切片操作

  • itertool.islice() 可以對迭代器和生成器做切片操作

In [3]: def count(n):...: while True:...: yield n...: n += 1...: In [5]: c = count(0) In [6]: c Out[6]: <generator object count at 0x7f92899b3c80> ----> 1 c[0] TypeError: 'generator' object has no attribute '__getitem__'import itertools In [10]: for x in itertools.islice(c, 10, 20):...: print(x) 10 11 12 13 14 15 16 17 18 19

跳過可迭代對象中的前一部分元素

  • itertools.dropwhile() 函數會?丟棄掉序列中的前面幾個元素
    例如,我們需要讀取一個文件,文件的開頭有一系列注釋行并不是我們想要的

from itertools import dropwhile with open('/etc/passwd') as f:for line in dropwhile(lambda line: line,startwith('#'), f):print(line, end='')

迭代所有可能的組合

  • 我們想對一些列元素的所有可能組合進行迭代

  • itrtools.permutations()函數接受一個元素集合,將其中所有元素重排列為所有可能的情況,并以元組的形式返回。

In [11]: from itertools import permutations In [12]: items = ['a', 'b', 'c'] In [13]: for p in permutations(items):...: print(p)...: ('a', 'b', 'c') ('a', 'c', 'b') ('b', 'a', 'c') ('b', 'c', 'a') ('c', 'a', 'b') ('c', 'b', 'a')#如果想得到較短的所有全排列,可以指定長度 In [14]: for p in permutations(items, 2):...: print(p) ('a', 'b') ('a', 'c') ('b', 'a') ('b', 'c') ('c', 'a') ('c', 'b')
  • itertools.combinations 不考慮元素間的實際順序,即('a', 'b')和('b', 'a')被認為是相同的組合形式。

  • 若想解除這一限制,可用combinations_with_replacement。

同時迭代多個序列

  • zip()函數可以用來迭代多個序列中的元素

>>>xvalues = [1,5,4,2,10,7] >>> yvalues = [101,78,37,15,62,99] >>> for x, y in zip(xvalues, yvalues): ... print(x, y) ... 1 101 5 78 4 37 2 15 10 62 7 99

在不同的容器中進行迭代

  • 我們需要對許多對象執行相同的操作,但是這些對象包含在不同的容器內,而我們希望可以避免寫出嵌套的循環處理,保持代碼的可讀性。使用itertools.chain()方法可以用來簡化這個任務。

from itertools import chainIn [18]: a = [1, 2, 3, 4] In [19]: b = ['x', 'y', 'z'] In [20]: for x in chain(a, b):...: print (x)...: 1 2 3 4 x y z

合并多個有序序列,再對整個有序序列進行迭代

  • heapq.merge()函數

>>>import heapq >>>a = [1,4,7,10] >>>b = [2,5,6,11] >>>for c in heapq.merge(a,b): ... print(c) ... 1 2 4 5 6 7 10 11

Chap 5 文件和IO

將輸出重定向到文件中

  • 只需要在print()函數加上file關鍵字參數即可

with open('somefile.txt', 'rt') as f:print('Hello World!', file=f)

以不同的分隔符或行結尾符完成打印

>>>print('GKY',1995,5,18, sep='-',end='!!\n') GKY-1995-5-18!!

在字符串上執行IO操作

  • 使用io.StringIO()和io.ByteIO()來創建類似于文件的對象,這些對象可操作字符串數據。

讀寫壓縮的數據文件

  • gzip和bz2模塊可以實現

import gzip with open('somefile.gz', 'rt') as f:text = f.read()import bz2 with open('somefile.bz2', 'rt') as f:text = f.read()import gzip with open('somefile.gz', 'wt') as f:f.write(text)import bz2 with open('somefile.bz', 'wt') as f:f.write(text)

將二進制數據讀到可變緩沖區中

  • 我們想將二進制數據直接讀取到一個可變緩沖區中,中間不經過任何拷貝環節。例如我們想原地修改數據再將它寫回到文件中去。

import os.path def read_into_buffer(filename):buf = bytearray(os.path.getsize(filename))with open(filename, 'rb') as f:f.readinto(buf)return bufwith open('sample.bin', 'wb') as f:f.write(b'hello world')buf = read_into_buffer('sample.bin') In [16]: buf Out[16]: bytearray(b'hello world')

序列化Python對象

  • 我們需要將Python對象序列化為字節流,這樣就可以將其保存到文件中、存儲到數據庫中或者通過網絡連接進行傳輸。

  • 序列化數據最常見的做法就是使用pickle模塊。

import pickle data = ... #some python object f = open('somefile', 'wb') pickle.dump(data,f)
  • 要將對象轉存為字符串,可以使用

import pickle data = ... #some python object f = open('somefile', 'wb') pickle.dumps(data,f)
  • 如果要從字節流中重新創建出對象,可以使用pickle.load()或者pickle.loads()


Chap 6 數據編碼與處理

讀寫JSON數據

  • 主要使用JSON模塊

  • 兩個主要的函數為json.dumps()和json.loads()

  • 如果是文件而不是字符串的話使用json.dump()和json.load()

解析簡單的XML文檔

  • xml.etree.ElementTree可以從簡單的XML文檔中提取數據

from urllib.request import urlopen from xml.etree.ElementTree import parseu = urlopen('http://planet.python.org/rss20.xml') doc = parse(u) In [24]: for item in doc.iterfind('channel/item'):....: title = item.findtext('title')....: date = item.findtext('pubDate')....: link = item.findtext('link')....: print (title)....: print(date)....: print(link)....: print()....:

往期精彩回顧適合初學者入門人工智能的路線及資料下載機器學習在線手冊深度學習在線手冊AI基礎下載(pdf更新到25集)備注:加入本站微信群或者qq群,請回復“加群”獲取一折本站知識星球優惠券,請回復“知識星球”喜歡文章,點個在看

總結

以上是生活随笔為你收集整理的推荐几个实用的Python“小伎俩”的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。