最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python 24個常用模塊編程必備知識庫

 更新時間:2026年03月12日 09:00:17   作者:東眠的魚  
本文給大家分享Python 24個常用模塊編程必備知識庫,本文通過實例代碼給介紹的非常詳細,感興趣的朋友跟隨小編一起看看吧

1.os - 系統(tǒng)交互大師

import os               # 查看當前工作目錄  
print(os.getcwd())      # 創(chuàng)建新目錄  
os.mkdir('new_folder')  # 列出指定目錄下的文件和子目錄  
for item in os.listdir('.'):  
print(item)  
  • os模塊是Python與操作系統(tǒng)對話的橋梁,讓你輕松進行文件和目錄操作,如獲取當前工作目錄、創(chuàng)建新目錄、列出目錄內(nèi)容等。

2.sys - 程序運行內(nèi)幕探索者

import sys           # 輸出Python版本信息  
print(sys.version)   # 打印命令行參數(shù)  
for arg in sys.argv:  
print(arg)  
  • sys模塊提供了訪問和控制Python解釋器運行時環(huán)境的方法,比如查看Python版本、獲取命令行參數(shù)等,幫你洞察程序內(nèi)部運作機制。

3.datetime - 時間管理專家

from datetime 
import datetime, timedelta  
# 獲取當前日期時間  
now = datetime.now()  
print(now)  
# 計算未來日期  
future_date = now + timedelta(days=30)  
print(future_date)  
  • datetime模塊讓處理日期和時間變得簡單直觀,你可以獲取當前時間、計算時間間隔、進行日期格式化等,是編寫與時間相關(guān)的程序不可或缺的好幫手。

4.math - 數(shù)學運算寶庫

import math    
# 計算圓面積  
radius = 5  
area = math.pi * radius ##  2  
print(area)    
# 計算最大公約數(shù)  
num1, num2 = ?, 21  
gcd = math.gcd(num1, num2)  
print(gcd)  
  • math模塊封裝了大量數(shù)學函數(shù)和常量,如求平方根、計算圓周率、求最大公約數(shù)等,滿足你的數(shù)學運算需求。

5.random - 隨機數(shù)生成魔術(shù)師

import random    
# 生成一個[0, 1)之間的隨機浮點數(shù)  
rand_float = random.random()  
print(rand_float)    
# 隨機從列表中選取一個元素  
choices = ['apple', 'banana', 'orange']  
random_choice = random.choice(choices)  
print(random_choice)  
  • random模塊負責生成各種類型的隨機數(shù),以及對列表等容器進行隨機抽樣,為你的程序添加不確定性,模擬真實世界的隨機行為。

6.csv - 數(shù)據(jù)導出導入能手

import csv    
# 寫入CSV文件  
with open('data.csv', 'w', newline='') as file:  
    writer = csv.writer(file)  
    writer.writerow(['Name', 'Age'])  
    writer.writerow(['Alice', 25])  
# 讀取CSV文件  
with open('data.csv', newline='') as file:  
    reader = csv.reader(file)  
    for row in reader:  
    print(row)  
  • csv模塊簡化了CSV(逗號分隔值)文件的讀寫操作,無論是保存數(shù)據(jù)還是分析外部數(shù)據(jù)源,它都是你的得力助手。

7.json - JSON數(shù)據(jù)處理好幫手

import json    
# 將Python對象轉(zhuǎn)換為JSON字符串  
data = {'name': 'John', 'age': 30}  
json_str = json.dumps(data)  
print(json_str)    
# 從JSON字符串解析回Python對象  
loaded_data = json.loads(json_str)  
print(loaded_data)  
  • json模塊用于序列化和反序列化JSON數(shù)據(jù),使得Python程序能夠輕松與使用JSON格式的Web服務(wù)或其他應(yīng)用程序交換數(shù)據(jù)。

8.requests - 網(wǎng)絡(luò)請求小飛俠

import requests    
# 發(fā)送GET請求并打印響應(yīng)內(nèi)容  
response = requests.get('https://api.github.com')  
print(response.text)  
  • requests庫簡化了HTTP請求的發(fā)送過程,無論是GET、POST還是其他方法,只需幾行代碼就能實現(xiàn),大大提升了網(wǎng)絡(luò)通信效率。

9.pandas - 數(shù)據(jù)分析與處理巨擘

import pandas as pd    
# 從CSV文件加載數(shù)據(jù)到DataFrame  
df = pd.read_csv('data.csv')    
# 查看前5行數(shù)據(jù)  
print(df.head())  
  • pandas庫提供了強大的數(shù)據(jù)結(jié)構(gòu)DataFrame,用于高效地進行數(shù)據(jù)分析、清洗、統(tǒng)計和可視化,是Python數(shù)據(jù)科學領(lǐng)域的核心工具之一。

10.numpy - 科學計算與數(shù)組操作神器

import numpy as np    
# 創(chuàng)建一個2x2的數(shù)組  
arr = np.array([[1, 2], [3, 4]])  
print(arr)    
# 計算數(shù)組元素之和  
sum_arr = np.sum(arr)  
print(sum_arr)  
  • numpy庫提供高性能的多維數(shù)組對象和豐富的數(shù)學函數(shù),是進行數(shù)值計算、機器學習、信號處理等領(lǐng)域開發(fā)的基礎(chǔ)庫。

11.matplotlib - 數(shù)據(jù)可視化魔法師

import matplotlib.pyplot as plt    
# 繪制簡單的折線圖  
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])  
plt.show()  
  • matplotlib庫用于創(chuàng)建靜態(tài)、動態(tài)、交互式的圖表,如折線圖、散點圖、柱狀圖等,是Python數(shù)據(jù)可視化的首選工具。

12.scipy - 科學計算全方位助手

from scipy.optimize 
import minimize    
# 定義目標函數(shù)  
def f(x):  
return x## 2 + 10*np.sin(x)    
# 使用優(yōu)化算法找到最小值  
result = minimize(f, x0=0)  
print(result.x)  
  • scipy庫包含眾多科學計算工具箱,如最優(yōu)化、插值、積分、信號處理、統(tǒng)計分析等,極大地擴展了Python在科學計算領(lǐng)域的能力。

13.re - 正則表達式獵手

import re    
# 使用正則表達式匹配郵箱地址  
pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'  
text = 'Contact me at alice@example.com or bob@gmail.com'  
matches = re.findall(pattern, text)  
print(matches)  
  • re模塊實現(xiàn)了正則表達式的支持,讓你能夠靈活、高效地進行文本模式匹配、查找、替換等操作。

14.threading - 多線程任務(wù)執(zhí)行者

import threading    
# 定義線程任務(wù)  
def thread_task(name):  
    print(f"Thread {name} started.")  
    # ... 執(zhí)行任務(wù) ...  
    print(f"Thread {name} finished.")    
# 創(chuàng)建并啟動兩個線程  
t1 = threading.Thread(target=thread_task, args=("Thread 1",))  
t2 = threading.Thread(target=thread_task, args=("Thread 2",))    
t1.start()  
t2.start()    
# 等待所有線程完成  
t1.join()  
t2.join()    
print("All threads finished.")  
  • threading模塊支持多線程編程,使程序能夠在同一時刻執(zhí)行多個任務(wù),提高程序并發(fā)性能和響應(yīng)速度。

15.timeit - 代碼性能測量儀

import timeit    
# 測試代碼塊執(zhí)行時間  
setup = "import math"  
statement = "math.factorial(100)"  
elapsed_time = timeit.timeit(setup=setup, stmt=statement, number=1000)  
print(f"Average execution time: {elapsed_time/1000:.6f} seconds")  
  • timeit模塊提供了一種簡便的方法來測量小段代碼的執(zhí)行時間,幫助開發(fā)者評估代碼性能,進行優(yōu)化。

16.unittest - 單元測試守護神

import unittest    
class TestMathFunctions(unittest.TestCase):  
def test_factorial(self):  
self.assertEqual(math.factorial(5), 120)  
def test_gcd(self):  
self.assertEqual(math.gcd(18, 24), 6)    
if __name__ == '__main__':  unittest.main()  
  • unittest模塊是Python標準庫中的單元測試框架,通過編寫測試用例來確保代碼的正確性和穩(wěn)定性。

17.argparse - 命令行參數(shù)解析器

import argparse    
parser = argparse.ArgumentParser(description='Process some integers.')  
parser.add_argument('integers', metavar='N', type=int, nargs='+',  
                   help='an integer for the accumulator')  
parser.add_argument('--sum', dest='accumulate', action='store_const',  
                   const=sum, default=max,  
                   help='sum the integers (default: find the max)')  
args = parser.parse_args()  
print(args.accumulate(args.integers))  
  • argparse模塊用于創(chuàng)建用戶友好的命令行接口,輕松處理程序接受的命令行參數(shù)。

18.logging - 程序日志記錄員

import logging    
logging.basicConfig(level=logging.INFO)  
logger = logging.getLogger(__name__)    
logger.info("This is an informative message.")  
logger.warning("Watch out! This might be a problem.")  
  • logging模塊提供了通用的日志記錄系統(tǒng),方便程序在運行過程中記錄調(diào)試信息、異常情況等,便于問題排查和跟蹤。

19.sqlite3 - 輕量級數(shù)據(jù)庫連接器

import sqlite3    
conn = sqlite3.connect('example.db')  
cursor = conn.cursor()    
cursor.execute('''CREATE TABLE stocks  
                 (date text, trans text, symbol text, qty real, price real)''')    
cursor.execute("INSERT INTO stocks VALUES ('202.jpg', 'BUY', 'RHAT', 100, 35.14)")    
conn.commit()  
conn.close()  
  • sqlite3模塊是Python內(nèi)置的SQLite數(shù)據(jù)庫驅(qū)動,允許程序直接操作SQLite數(shù)據(jù)庫,進行數(shù)據(jù)存儲、查詢等操作。

20.hashlib - 哈希函數(shù)計算者

import hashlib    
message = "Hello, world!".encode()  
digest = hashlib.sha256(message).hexdigest()  
print(digest)  
  • hashlib模塊提供了多種安全的哈希函數(shù),如SHA-256,用于生成消息摘要或校驗數(shù)據(jù)完整性。

21.xml.etree.ElementTree - XML解析與生成伙伴

import xml.etree.ElementTree as ET    
root = ET.Element("root")  
child = ET.SubElement(root, "child", name="element1")  
ET.SubElement(child, "grandchild").text = "Some text"    
tree = ET.ElementTree(root)  
tree.write("output.xml")  
  • xml.etree.ElementTree模塊提供了處理XML文檔的API,包括解析、構(gòu)建、搜索XML樹等功能。

22.shutil - 文件與目錄操作好伙伴

import shutil  
shutil.copyfile('source.txt', 'destination.txt')  
shutil.move('old_file.txt', 'new_file.txt')  
shutil.rmtree('directory_to_remove')  
  • shutil模塊提供了高級文件和目錄操作功能,如復制、移動文件,刪除目錄及其內(nèi)容等。

23.itertools - 生成器與迭代器魔法工廠

import itertools    
combinations = itertools.combinations(range(4), 2)  
for combo in combinations:  
print(combo)  
  • itertools模塊包含了一系列高效且內(nèi)存友好的迭代器函數(shù),如生成組合、排列、無限序列等,極大豐富了Python的循環(huán)結(jié)構(gòu)。

24.functools - 高級函數(shù)工具箱

import functools  @functools.lru_cache(maxsize=32)  
def fib(n):  if n < 2:  
return n  
return fib(n-1) + fib(n-2)    
print(fib(10))  
  • functools模塊提供了許多用于處理函數(shù)的工具,如裝飾器、高階函數(shù)等,有助于編寫更簡潔、更高效的代碼。

總結(jié)

到此這篇關(guān)于Python 24個常用模塊編程必備知識庫的文章就介紹到這了,更多相關(guān)Python常用模塊內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論

固原市| 酒泉市| 扎赉特旗| 都安| 咸宁市| 清苑县| 周至县| 沛县| 南江县| 慈利县| 布尔津县| 呼伦贝尔市| 和顺县| 道真| 临夏市| 祁门县| 丹阳市| 巴林左旗| 方城县| 来安县| 昂仁县| 乳山市| 论坛| 龙门县| 潍坊市| 青海省| 沭阳县| 凯里市| 宣化县| 黄大仙区| 上虞市| 夹江县| 玉屏| 揭阳市| 陇南市| 宜州市| 西城区| 武乡县| 太湖县| 井陉县| 民勤县|