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

歡迎訪問 生活随笔!

生活随笔

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

python

python标准库(二)

發布時間:2023/12/10 python 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python标准库(二) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

格式化輸出

  • reprlib 庫用來格式化
>>> import reprlib >>> reprlib.repr(set('aabbccddeeeff')) "{'a', 'b', 'c', 'd', 'e', 'f'}" >>>
  • 對集合能排序
>>> reprlib.repr(set('fdajfejaa')) "{'a', 'd', 'e', 'f', 'j'}" >>>
  • pprint庫用來縮進和空行,輸出的內置對象和用戶自定義對象能被解釋器直接讀取。
>>> p = [[['red', 'yellow'], ['pink']], ['black'], 'blue'] >>> pprint.pprint(p, width=5) [[['red','yellow'],['pink']],['black'],'blue'] >>>
  • textwrap用來格式化段落
>>> import textwrap as tw >>> doc = ''' she is so gorgeous! I really like her ! ... May the distance between her want and I am weak . ... Try Hard... Learning your all time... aseert...''' >>> print(tw.fill(doc, width=40)) # 每行40個字母she is so gorgeous! I really like her ! May the distance between her want and I am weak . Try Hard... Learning your all time... aseert... >>>
  • Locale 模塊處理與特定地域相關的數據格式。
>>> import locale >>> locale.setlocale(locale.LC_ALL, 'English_United States.1252') 'English_United States.1252' >>> >>> conv = locale.localeconv() >>> conv {'int_curr_symbol': 'USD', 'currency_symbol': '$', 'mon_decimal_point': '.', 'mon_thousands_sep': ',', 'mon_grouping': [3, 0], 'positive_sign': '', 'negative_sign': '-', 'int_frac_digits': 2, 'frac_digits': 2, 'p_cs_precedes': 1, 'p_sep_by_space': 0, 'n_cs_precedes': 1, 'n_sep_by_space': 0, 'p_sign_posn': 3, 'n_sign_posn': 0, 'decimal_point': '.', 'thousands_sep': ',', 'grouping': [3, 0]} >>> >>> x = 12345.6 >>> locale.format_string("%d", x, grouping =True) # 對數字進行分隔 '12,345' >>> locale.format_string("%s%*.f", (conv['currency_symbol'], conv['frac_digits'], x), grouping=True) '$12,346'

模塊

  • string模塊的Template 類

    用于格式化的 占位符($(字母,數字,下劃線)) $ + 標識符 , 如果在外面加上{} 后面可直接跟字母,數字(不用空格)。

T = Template('${k}like $kk') T.substitute(k='', kk='') >>> from string import Template # 導入摸板>>> t = Template('${she} is so $how') # $加標識符表示占位>>> t.substitute(she='she', how='adorable') # 把占位符給替換了'she is so adorable'>>># 如果,參數不完整>>> t = Template('return the $item to $owner')>>> t.substitute(dict(item='unladen swallow')) # 未提供 owner的參數Traceback (most recent call last):File "<stdin>", line 1, in <module>File "D:\softWare\python\python3.7\lib\string.py", line 132, in substitutereturn self.pattern.sub(convert, self.template)File "D:\softWare\python\python3.7\lib\string.py", line 125, in convertreturn str(mapping[named])KeyError: 'owner'>>># 用戶也可能出現上面滴參數不完整情況 用safe_substitute>>> t.safe_substitute(dict(item='unladen swallow'))'return the unladen swallow to $owner'>>>
  • 對瀏覽器照片重命名
>>> import time, os.path>>> photofiles = ['img_102.jpg', 'img_104.jpg', 'img_106.jpg']>>> class BatchRename(Template): # 繼承模板類... delimiter = '%'...>>> fmt = input('輸入重命名的樣式(%d-date %n-sequm %f-format): ')輸入重命名的樣式(%d-date %n-sequm %f-format): lel_%n%f>>> fmt'lel_%n%f'>>> br = BatchRename(fmt)>>> date = time.strftime('%d%b%y')>>> date'13May20'>>> for i, filename in enumerate(photofiles):... base, ext = os.path.splitext(filename)... newname = br.substitute(d=date, n=i, f=ext)... print('{0} --> {1}'.format(filename, newname))...img_102.jpg --> lel_0.jpgimg_104.jpg --> lel_1.jpgimg_106.jpg --> lel_2.jpg>>>

多線程

  • 線程是一種對于非順序依賴的多個任務進行解耦的技術。
  • 多線程可以提高應用的響應效率 當接收用戶輸入的同時,保持其他任務在后臺運行。
  • 應用場景,將i/o 和 計算運行在兩個并行的線程中。
import zipfile, threadingclass AsyncZip(threading.Thread):def __init__(self, infile, outfile): # 構造輸入輸出文件threading.Thread.__init__(self)self.infile = infileself.outfile = outfiledef run(self):f = zipfile.ZipFile(self.outfile, 'w', zipfile.ZIP_DEFLATED) # 打開文件只寫f.write(self.infile) # 壓縮文件f.close()print('完成后臺壓縮...', self.infile)# 測試 background = AsyncZip('e:/MyStudy/bitQianBlog/python/pythonBasic/StandLib/test.txt', 'output.zip') background.start()print('主程序后臺運行中...')background.join() # 等待后臺任務完成...print('主程序一直等待后臺任務完成...')

  • 日志記錄 – logging模塊
>>> import logging as log # 日志記錄模塊 >>> log.debug('解決bug信息...') >>> log.info('消息') >>> log.warning('警告, 配置文件%s找不到', 'server.conf') WARNING:root:警告, 配置文件server.conf找不到 >>> log.error('存在錯誤') ERROR:root:存在錯誤 >>> log.critical('判定錯誤 -- 關機') CRITICAL:root:判定錯誤 -- 關機 >>>

弱引用weakdef

  • py 會自動進行內存管理(garbage collection)。
  • 當某個對象的最后一個引用被移除后 不久就會釋放所占的內存。
  • weakdef 可以不創建引用,就可跟蹤其它對象。
  • 當對象不再需要時,它將自動從一個弱引用表中被移除,并為弱引用對象觸發一個回調。
  • 典型應用包括對創建開銷較大的對象進行緩存:
import weakref, gc class A:def __init__(self, value):self.value = valuedef __repr__(self):return str(self.value)a = A(10) # 創建一個引用 d = weakref.WeakValueDictionary() d['primary'] = a print(d['primary']) # 10del a # 移除引用print(gc.collect()) # 0print(d['primary']) # KeyError: 'primary'
  • 用于操作列表的工具
array模塊提供的array()對象,類似列表,但只儲存一種數據類型>>> # 以兩個字節為存儲單元的無符號d二進制數值的數組(類型碼為 'H')>>> from array import array>>> a = array([1, 2, 3, 4])Traceback (most recent call last):File "<stdin>", line 1, in <module>TypeError: array() argument 1 must be a unicode character, not list>>> a = array('H', [1, 2, 3, 4])>>> sum(a)10>>> a[0:2] # 切片array('H', [1, 2])>>>>>> aarray('H', [1, 2, 3, 4])collections 的 deque() 對象 隊列,增刪快,查找慢>>> from collections import deque>>> d = deque(['a', 'b', 'c', 'd'])>>> d.append('e')>>> ddeque(['a', 'b', 'c', 'd', 'e'])>>> print('出隊, ', d.popleft())出隊, a>>> ddeque(['b', 'c', 'd', 'e'])bisect(平分,二等分)模塊操作排序列表的函數>>> import bisect as bi>>> scores = [(100, 'ruby'), (200, 'python'), (400, 'java'), (500, 'c')]>>> bi.insort(scores, (300, 'javascript')) # 按分數排序>>> scores[(100, 'ruby'), (200, 'python'), (300, 'javascript'), (400, 'java'), (500, 'c')]heapq 模塊 基于列表來實現堆函數。 你可選擇性的排序你要的列表。>>> from heapq import heapify, heappop, heappush>>> data = [2, 1, 4, 7, 5, 0, 9, 8, 3, 6]>>> heapify(data) # 按堆順序重新排列列表>>> data[0, 1, 2, 3, 5, 4, 9, 8, 7, 6]>>> data[0, 1, 2, 3, 5, 4, 9, 8, 7, 6]>>> heappush(data, -1) # 添加-1>>> data[-1, 0, 2, 3, 1, 4, 9, 8, 7, 6, 5]>>> heappop(data) # 移除-1-1>>> data[0, 1, 2, 3, 5, 4, 9, 8, 7, 6]>>> [heappop(data) for i in range(3)] # 從堆中移除前三個數[0, 1, 2]>>> data[3, 5, 4, 6, 8, 7, 9]

decimal模塊

? 財務應用和其他需要精確十進制表示的用途,
? 控制精度,
? 控制四舍五入以滿足法律或監管要求,
? 跟蹤有效小數位,或
? 用戶期望結果與手工完成的計算相匹配的應用程序。

  • 用decimal計算,和直接計算
>>> round(Decimal('0.70') * Decimal('1.05'), 2)Decimal('0.74')>>>>>> round(0.70 * 1.05, 2)0.73
  • 對比float的浮點運算 和 比較
>>> Decimal('1.00') % Decimal('0.10')Decimal('0.00')>>>>>> 1.00 % 0.100.09999999999999995>>>>>> sum([Decimal('0.1')*10]) == Decimal('1.0')True>>> s = sum([0.1] * 10)>>> s0.9999999999999999>>> s == 1.0False
  • decimal提供的精度
>>> getcontext().prec = 36>>> Decimal(1) / Decimal(7)Decimal('0.142857142857142857142857142857142857')

ps:學習筆記。請看:
python標準庫(一)

總結

以上是生活随笔為你收集整理的python标准库(二)的全部內容,希望文章能夠幫你解決所遇到的問題。

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