自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Python 備忘清單,一眼掃完核心知識點

開發(fā) 前端
這份Python備忘請單是一個全面而實用的Python編程快速參考資源。它覆蓋了從基礎(chǔ)的數(shù)據(jù)類型、變量賦值、控制流程、函數(shù)、類與對象、文件處理、異常處理到更高級的主題。

數(shù)據(jù)類型

介紹Python中的不同數(shù)據(jù)類型,包括整數(shù)、浮點數(shù)、字符串和布爾值。

int_num = 42  # 整數(shù)
float_num = 3.14  # 浮點數(shù)
string_var = "Hello, Python!"  # 字符串
bool_var = True  # 布爾值

變量和賦值

展示如何在Python中聲明變量并給它們賦值。

x = 10  # 變量賦值
y = "Python"

列表 & 元組

解釋了列表和元組的創(chuàng)建,它們是Python中用于存儲序列的兩種主要數(shù)據(jù)結(jié)構(gòu)。

my_list = [1, 2, 3, "Python"]  # 列表
my_tuple = (1, 2, 3, "Tuple")  # 元組

字典

字典是Python中用于存儲鍵值對的另一種數(shù)據(jù)結(jié)構(gòu)。

my_dict = {'name': 'John', 'age': 25, 'city': 'Pythonville'}  # 字典

控制流程

控制流程語句,如if-elif-else和for循環(huán),用于控制程序的執(zhí)行流程。

if x > 0:
    print("Positive")
elif x == 0:
    print("Zero")
else:
    print("Negative")
for item in my_list:
    print(item)
while condition:
    # code

函數(shù)

函數(shù)定義和調(diào)用的示例,展示了如何創(chuàng)建一個簡單的函數(shù)。

def greet(name="User"): 
    return f"Hello, {name}!"
result = greet("John")

類 & 對象

類和對象的使用,演示了如何定義一個類并創(chuàng)建類的實例。

class Dog:
    def __init__(self, name): 
        self.name = name
    def bark(self): 
        print("Woof!")

my_dog = Dog("Buddy")
my_dog.bark()

文件處理

文件操作的基本示例,包括讀取和寫入文件。

with open("file.txt", "r") as file: 
    content = file.read()

with open("new_file.txt", "w") as new_file: 
    new_file.write("Hello, Python!")

異常處理

異常處理的用法,展示了如何用try-except語句來處理可能的錯誤。

try: 
    result = 10 / 0 
except ZeroDivisionError: 
    print("Cannot divide by zero!")
finally: 
    print("Execution completed.")

庫 & 模塊

展示如何導入和使用Python的內(nèi)置庫和模塊。

import math
from datetime import datetime 
result = math.sqrt(25) 
current_time = datetime.now()

列表推導式

列表推導式的使用,提供了一種簡潔的方法來創(chuàng)建列表。

squares = [x**2 for x in range(5)]  # 列表推導式

Lambda 函數(shù)

Lambda函數(shù)的用法,展示了如何創(chuàng)建匿名函數(shù)。

add = lambda x, y: x + y 
result = add(2, 3)

虛擬環(huán)境

虛擬環(huán)境的創(chuàng)建和使用,用于隔離項目依賴。

# 創(chuàng)建虛擬環(huán)境
python -m venv myenv

# 激活虛擬環(huán)境
source myenv/bin/activate  # 在Unix或MacOS
myenv\Scripts\activate  # 在Windows

# 停用虛擬環(huán)境
deactivate

包管理

包管理工具pip的使用,用于安裝和管理Python包。

# 安裝包
pip install package_name

# 列出已安裝的包
pip list

# 創(chuàng)建requirements.txt
pip freeze > requirements.txt

# 從requirements.txt安裝包
pip install -r requirements.txt

與JSON的交互

JSON數(shù)據(jù)格式的轉(zhuǎn)換,展示了如何將Python對象轉(zhuǎn)換為JSON格式,以及反向操作。

import json
# 將Python對象轉(zhuǎn)換為JSON
json_data = json.dumps({"name": "John", "age": 25})

# 將JSON轉(zhuǎn)換為Python對象
python_obj = json.loads(json_data)

正則表達式

正則表達式的使用,用于字符串的搜索和操作。

import re
pattern = r'\d+'  # 匹配一個或多個數(shù)字
result = re.findall(pattern, "There are 42 apples and 123 oranges.")

與日期的交互

日期和時間的處理,展示了如何獲取當前日期和計算未來日期。

from datetime import datetime, timedelta
current_date = datetime.now()
future_date = current_date + timedelta(days=7)

列表操作

列表的操作,包括過濾、映射和歸約。

numbers = [1, 2, 3, 4, 5]
# 過濾
evens = list(filter(lambda x: x % 2 == 0, numbers))

# 映射
squared = list(map(lambda x: x**2, numbers))

# 歸約 (需要functools)
from functools import reduce
product = reduce(lambda x, y: x * y, numbers)

字典操作

字典的操作,包括獲取值和字典推導式。

my_dict = {'a': 1, 'b': 2, 'c': 3}
# 獲取值
value = my_dict.get('d', 0)

# 字典推導式
squared_dict = {key: value**2 for key, value in my_dict.items()}

線程并發(fā)

線程的使用,展示了如何在Python中創(chuàng)建和管理線程。

import threading
def print_numbers(): 
    for i in range(5): 
        print(i)
thread = threading.Thread(target=print_numbers)
thread.start()

Asyncio并發(fā)

Asyncio的使用,展示了如何在Python中進行異步編程。

import asyncio
async def print_numbers(): 
    for i in range(5): 
        print(i)
        await asyncio.sleep(1)
asyncio.run(print_numbers())

Web Scraping with Beautiful Soup

使用Beautiful Soup進行網(wǎng)頁抓取。

from bs4 import BeautifulSoup
import requests
url = "https://example.com"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
title = soup.title.text

RESTful API with Flask

使用Flask框架創(chuàng)建RESTful API。

from flask import Flask, jsonify, request
app = Flask(__name__)

@app.route('/api/data', methods=['GET'])
def get_data():
    data = {'key': 'value'}
    return jsonify(data)

if __name__ == '__main__':
    app.run(debug=True)

單元測試 with unittest

使用unittest進行單元測試。

import unittest

def add(x, y): 
    return x + y

class TestAddition(unittest.TestCase):
    def test_add_positive_numbers(self): 
        self.assertEqual(add(2, 3), 5)

if __name__ == '__main__':
    unittest.main()

數(shù)據(jù)庫交互 with SQLite

使用SQLite數(shù)據(jù)庫的交互。

import sqlite3
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
# 執(zhí)行SQL查詢
cursor.execute('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name')
# 提交更改
conn.commit()
# 關(guān)閉連接
conn.close()

文件處理

文件的讀寫操作。

# 寫入文件
with open('example.txt', 'w') as file:
    file.write('Hello, Python!')

# 讀取文件
with open('example.txt', 'r') as file:
    content = file.read()

錯誤處理

錯誤處理的示例。

try: 
    result = 10 / 0 
except ZeroDivisionError as e: 
    print(f"Error: {e}")
except Exception as e: 
    print(f"Unexpected Error: {e}")
else: 
    print("No errors occurred.")
finally: 
    print("This block always executes.")

Python Decorators

使用裝飾器的示例。

def decorator(func): 
    def wrapper(): 
        print("Before function execution")
        func() 
        print("After function execution")
    return wrapper 

@decorator 
def my_function(): 
    print("Inside the function")

my_function()

枚舉 with Enums

使用枚舉類型的示例。

from enum import Enum

class Color(Enum): 
    RED = 1 
    GREEN = 2 
    BLUE = 3
print(Color.RED)

集合操作

集合的基本操作,包括并集、交集和差集。

set1 = {1, 2, 3}
set2 = {3, 4, 5}
# 并集
union_set = set1 | set2
# 交集
intersection_set = set1 & set2
# 差集
difference_set = set1 - set2

列表推導式

使用列表推導式來生成特定條件的列表。

numbers = [1, 2, 3, 4, 5]
# 偶數(shù)的平方
squares = [x**2 for x in numbers if x % 2 == 0]

Lambda 函數(shù)

使用Lambda函數(shù)進行簡單的函數(shù)定義。

add = lambda x, y: x + y
result = add(3, 5)

線程與Concurrent.futures

使用concurrent.futures進行線程池操作。

from concurrent.futures import ThreadPoolExecutor

def square(x): 
    return x**2

with ThreadPoolExecutor() as executor: 
    results = executor.map(square, [1, 2, 3, 4, 5])

國際化 (i18n) with gettext

使用gettext進行國際化。

import gettext

# 設(shè)置語言
lang = 'en_US'
_ = gettext.translation('messages', localedir='locale', languages=[lang]).gette
print(_("Hello, World!"))

虛擬環(huán)境

虛擬環(huán)境的創(chuàng)建、激活和停用。

# 創(chuàng)建虛擬環(huán)境
python -m venv myenv

# 激活虛擬環(huán)境
source myenv/bin/activate  # 在Unix/Linux
myenv\Scripts\activate  # 在Windows

# 停用虛擬環(huán)境
deactivate

日期操作

日期的格式化和天數(shù)的添加。

from datetime import datetime, timedelta

now = datetime.now()
# 格式化日期
formatted_date = now.strftime('%Y-%m-%d %H:%M:%S')
# 給日期添加天數(shù)
future_date = now + timedelta(days=7)

字典操作

字典的值獲取和遍歷。

my_dict = {'name': 'John', 'age': 30}
# 獲取值,并設(shè)置默認值
age = my_dict.get('age', 25)
# 遍歷鍵和值
for key, value in my_dict.items():
    print(f"{key}: {value}")

正則表達式

使用正則表達式匹配字符串中的數(shù)字。

import re
text = "Hello, 123 World!"
# 匹配數(shù)字
numbers = re.findall(r'\d+', text)

生成器

使用生成器生成一系列值。

def square_numbers(n): 
    for i in range(n): 
        yield i**2

squares = square_numbers(5)

數(shù)據(jù)庫交互 with SQLite

使用SQLite數(shù)據(jù)庫進行查詢。

import sqlite3
# 連接SQLite數(shù)據(jù)庫
conn = sqlite3.connect('mydatabase.db')
cursor = conn.cursor()
# 執(zhí)行SQL查詢
cursor.execute('SELECT * FROM mytable')

操作ZIP文件

使用zipfile模塊創(chuàng)建和解壓ZIP文件。

import zipfile

with zipfile.ZipFile('archive.zip', 'w') as myzip:
    myzip.write('file.txt')

with zipfile.ZipFile('archive.zip', 'r') as myzip:
    myzip.extractall('extracted')

Web 爬蟲 requests 和 BeautifulSoup

使用requests和BeautifulSoup進行網(wǎng)頁抓取。

import requests
from bs4 import BeautifulSoup

url = 'https://example.com'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# 從HTML提取數(shù)據(jù)
title = soup.title.text

發(fā)送電子郵件 with smtplib

使用smtplib發(fā)送電子郵件。

import smtplib
from email.mime.text import MIMEText

# 設(shè)置郵件服務(wù)器
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()

# 登錄郵箱賬戶
server.login('your_email@gmail.com', 'your_password')

# 發(fā)送郵件
msg = MIMEText('Hello, Python!')
msg['Subject'] = 'Python Email'
server.sendmail('your_email@gmail.com', 'recipient@example.com', msg.as_string())

操作JSON文件

JSON文件的讀寫操作。

import json
data = {'name': 'John', 'age': 30}

# 寫入JSON文件
with open('data.json', 'w') as json_file:
    json.dump(data, json_file)

# 從JSON文件讀取
with open('data.json', 'r') as json_file:
    loaded_data = json.load(json_file)

總結(jié)

這份Python備忘請單是一個全面而實用的Python編程快速參考資源。它覆蓋了從基礎(chǔ)的數(shù)據(jù)類型、變量賦值、控制流程、函數(shù)、類與對象、文件處理、異常處理到更高級的主題,如列表推導式、Lambda函數(shù)、虛擬環(huán)境、包管理、JSON操作、正則表達式、日期處理、集合操作、線程并發(fā)、異步編程、Web抓取、RESTful API開發(fā)、單元測試、數(shù)據(jù)庫交互、裝飾器、枚舉、國際化、生成器、ZIP文件操作、電子郵件發(fā)送等多個方面。

總的來說,備忘清單是為不同水平的Python開發(fā)者設(shè)計的,幫助大家快速查找和回顧編程中的關(guān)鍵概念和實用技巧。

責任編輯:華軒 來源: 哈希編程
相關(guān)推薦

2021-01-06 13:52:19

zookeeper開源分布式

2024-11-04 09:00:00

Java開發(fā)

2021-12-30 08:17:27

Springboot數(shù)據(jù)訪問DataSourceB

2025-01-07 14:10:46

SpringBoot開發(fā)Java

2020-11-06 00:50:16

JavaClassLoaderJVM

2021-01-15 08:35:49

Zookeeper

2020-10-26 10:40:31

Axios前端攔截器

2022-10-29 08:55:19

頁面react

2025-03-26 11:30:40

2021-04-13 08:25:12

測試開發(fā)Java注解Spring

2020-05-19 14:40:08

Linux互聯(lián)網(wǎng)核心

2022-04-08 07:51:31

JavaJVM垃圾回收

2024-09-18 10:40:00

AI生成

2024-06-04 14:07:00

2023-08-07 14:44:56

Socket文件描述符

2018-01-11 15:15:13

2021-12-27 10:20:46

JavaNetty網(wǎng)絡(luò)

2020-05-21 12:59:51

邊緣存儲存儲物聯(lián)網(wǎng)

2017-03-07 13:03:34

AndroidView知識問答

2021-09-06 08:31:11

Kafka架構(gòu)主從架構(gòu)
點贊
收藏

51CTO技術(shù)棧公眾號