Common Built‑in Functions and Popular Third‑Party Libraries in Python with Examples
This article lists essential Python built‑in functions, introduces widely used third‑party libraries such as NumPy, Pandas, Matplotlib, Scikit‑learn, TensorFlow, Requests, Beautiful Soup, Flask/Django, SQLAlchemy, SciPy, Pillow and OpenCV, and provides concrete code examples demonstrating their usage.
Python provides a set of built‑in functions such as print() , len() , type() , int() , float() , str() , input() , range() , list() , tuple() , set() , dict() , sorted() , max() , min() , sum() , map() , filter() , zip() , open() , help() and dir() , which are essential for everyday programming tasks.
Popular third‑party libraries extend Python’s capabilities, including NumPy, Pandas, Matplotlib, Scikit‑learn, TensorFlow / PyTorch, Requests, Beautiful Soup, Flask / Django, SQLAlchemy, SciPy, Pillow and OpenCV, each serving domains such as scientific computing, data analysis, visualization, machine learning, web development and computer vision.
Example code snippets demonstrate the usage of these functions and libraries:
Built‑in function examples
# 示例代码
message = "Hello, World!"
print(message)
# 使用场景
# 当你需要在控制台输出信息时使用。 # 示例代码
my_list = [1, 2, 3, 4, 5]
length = len(my_list)
print(f"The length of the list is: {length}")
# 使用场景
# 当你需要知道容器(如列表、字典、字符串等)中元素的数量时使用。 # 示例代码
data = 42
print(type(data)) # 输出:
# 使用场景
# 当你需要检查变量或对象的数据类型时使用。 # 示例代码
number_str = "100"
number_int = int(number_str)
number_float = float(number_str)
print(f"Integer: {number_int}, Float: {number_float}") # 输出: Integer: 100, Float: 100.0
# 使用场景
# 当你需要将数据从一种类型转换为另一种类型时使用。 # 示例代码
name = input("Please enter your name: ")
print(f"Hello, {name}!")
# 使用场景
# 当你需要从用户那里获取输入时使用。 # 示例代码
for i in range(5):
print(i) # 输出: 0 1 2 3 4
# 使用场景
# 当你需要生成一系列连续的数字,通常用于循环计数时使用。 # 示例代码
numbers_list = list(range(5))
numbers_tuple = tuple(numbers_list)
numbers_set = set(numbers_list)
numbers_dict = dict(enumerate(numbers_list))
print(f"List: {numbers_list}")
print(f"Tuple: {numbers_tuple}")
print(f"Set: {numbers_set}")
print(f"Dict: {numbers_dict}")
# 使用场景
# 当你需要创建特定类型的容器时使用。 # 示例代码
unsorted_list = [5, 2, 9, 1, 5, 6]
sorted_list = sorted(unsorted_list)
print(sorted_list) # 输出: [1, 2, 5, 5, 6, 9]
# 使用场景
# 当你需要对可迭代对象进行排序时使用。 # 示例代码
numbers = [5, 2, 9, 1, 5, 6]
print(f"Max: {max(numbers)}, Min: {min(numbers)}" ) # 输出: Max: 9, Min: 1
# 使用场景
# 当你需要找到序列中的最大值或最小值时使用。 # 示例代码
numbers = [5, 2, 9, 1, 5, 6]
total = sum(numbers)
print(f"Sum: {total}") # 输出: Sum: 28
# 使用场景
# 当你需要计算所有元素的总和时使用。 # 示例代码
def square(x):
return x * x
numbers = [1, 2, 3, 4]
squared_numbers = map(square, numbers)
print(list(squared_numbers)) # 输出: [1, 4, 9, 16]
# 使用场景
# 当你需要将一个函数应用于可迭代对象中的每个元素并返回结果时使用。 # 示例代码
def is_even(x):
return x % 2 == 0
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(is_even, numbers)
print(list(even_numbers)) # 输出: [2, 4, 6]
# 使用场景
# 当你需要筛选出满足条件的元素时使用。 # 示例代码
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
pairs = zip(names, ages)
print(list(pairs)) # 输出: [('Alice', 25), ('Bob', 30), ('Charlie', 35)]
# 使用场景
# 当你需要将多个可迭代对象中的元素配对时使用。 # 示例代码
with open('example.txt', 'w') as file:
file.write("This is a test.")
# 使用场景
# 当你需要读写文件时使用。 # 示例代码
help(str.split) # 显示关于str.split的帮助文档
# 使用场景
# 当你需要查看某个对象或模块的帮助文档时使用。 # 示例代码
print(dir(str)) # 列出字符串类的所有属性和方法
# 使用场景
# 当你想知道一个对象有哪些属性和方法时使用。Third‑party library examples
import numpy as np
# 创建一个数组
array = np.array([1, 2, 3, 4, 5])
print(array) # 输出: [1 2 3 4 5]
# 使用场景
# NumPy 是用于科学计算的基础库,特别适用于处理大量数值数据。
# 它提供了高效的多维数组对象和各种操作这些数组的函数。 import pandas as pd
# 创建一个简单的DataFrame
data = {'Name': ['John', 'Anna', 'Peter'], 'Age': [28, 24, 35]}
df = pd.DataFrame(data)
print(df)
# 使用场景
# Pandas 提供了强大的数据结构(如DataFrame)来处理和分析结构化数据。
# 它非常适合于数据分析、数据清洗和数据预处理。 import matplotlib.pyplot as plt
# 绘制一个简单的折线图
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
plt.plot(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Simple Line Plot')
plt.show()
# 使用场景
# Matplotlib 是一个非常强大的绘图库,可以用来创建静态、动态及交互式的可视化图表。
# 它广泛应用于科研论文、报告等需要高质量图形的地方。 from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
# 加载数据集
iris = datasets.load_iris()
X, y = iris.data, iris.target
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 创建并训练KNN分类器
knn = KNeighborsClassifier(n_neighbors=3)
knn.fit(X_train, y_train)
# 预测
predictions = knn.predict(X_test)
print(predictions)
# 使用场景
# Scikit‑learn 是一个简单而有效的机器学习库,包含了大量的监督和无监督学习算法。
# 它常被用于快速原型设计和实现机器学习模型。 # 这里以 TensorFlow 为例:
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
# 构建一个简单的神经网络模型
model = Sequential([
Dense(10, activation='relu', input_shape=(784,)),
Dense(10, activation='softmax')
])
# 编译模型
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
# 打印模型概述
model.summary()
# 使用场景
# TensorFlow 和 PyTorch 是两个主流的深度学习框架,支持构建复杂的神经网络模型。
# 它们广泛应用于图像识别、自然语言处理等领域。 import requests
# 发送GET请求
response = requests.get('https://api.github.com')
print(response.status_code) # 输出状态码
print(response.json()) # 输出响应内容为JSON格式
# 使用场景
# Requests 库使得发送HTTP请求变得非常容易。
# 它常用于与Web API进行交互,比如获取或提交数据。 from bs4 import BeautifulSoup
import requests
# 获取网页内容
url = 'http://example.com'
page = requests.get(url).text
soup = BeautifulSoup(page, 'html.parser')
# 查找所有的链接
links = soup.find_all('a')
for link in links:
print(link.get('href'))
# 使用场景
# Beautiful Soup 用于解析HTML和XML文档,从中提取信息。
# 它经常被用在网页抓取和数据挖掘项目中。 # 这里以 Flask 为例:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return "Hello, World!"
if __name__ == '__main__':
app.run(debug=True)
# 使用场景
# Flask 和 Django 是Python的Web框架,用于快速开发Web应用。
# Flask 更轻量级且灵活,适合小型项目;Django 功能更全面,适合大型应用。 from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
age = Column(Integer)
engine = create_engine('sqlite:///example.db')
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
# 添加新用户
new_user = User(name='Alice', age=30)
session.add(new_user)
session.commit()
# 查询所有用户
users = session.query(User).all()
for user in users:
print(user.name, user.age)
# 使用场景
# SQLAlchemy 是一个ORM工具,它允许开发者通过类来定义数据库表,并以面向对象的方式操作数据库。
# 它简化了数据库操作,提高了代码的可读性和维护性。 from scipy.optimize import minimize
# 定义目标函数
def objective(x):
return x[0]**2 + x[1]**2
# 初始猜测值
x0 = [2, 3]
# 最小化目标函数
result = minimize(objective, x0)
print(result.x) # 输出最小值对应的x
# 使用场景
# SciPy 包含了许多科学计算中常用的数学算法,如优化、积分、插值等。
# 它是科学计算领域的一个重要工具。 pip install pillow from PIL import Image, ImageFilter, ImageDraw, ImageFont
# 打开一张图片
image = Image.open("example.jpg")
# 显示图片
image.show()
# 转换图片模式
gray_image = image.convert("L")
gray_image.show()
# 应用滤镜
blurred_image = image.filter(ImageFilter.BLUR)
blurred_image.show()
# 缩放图片
resized_image = image.resize((100, 100))
resized_image.show()
# 旋转图片
rotated_image = image.rotate(90)
rotated_image.show()
# 在图片上绘制文字
draw = ImageDraw.Draw(image)
font = ImageFont.truetype("arial.ttf", 24)
draw.text((10, 10), "Hello, Pillow!", font=font, fill=(255, 0, 0))
# 保存处理后的图片
image.save("output.jpg")
# 使用场景
# Pillow 适用于需要进行图像处理的各种应用,如图像编辑软件、网站中的图片处理等。
# 它可以读取和写入多种图像格式,并提供了丰富的图像处理功能。 pip install opencv-python import cv2
import numpy as np
# 读取图片
image = cv2.imread("example.jpg")
# 显示图片
cv2.imshow("Original Image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
# 转换成灰度图
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2.imshow("Gray Image", gray_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
# 应用高斯模糊
blurred_image = cv2.GaussianBlur(gray_image, (5, 5), 0)
cv2.imshow("Blurred Image", blurred_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
# 边缘检测
edges = cv2.Canny(blurred_image, 50, 150)
cv2.imshow("Edges", edges)
cv2.waitKey(0)
cv2.destroyAllWindows()
# 保存处理后的图片
cv2.imwrite("output_edges.jpg", edges)
# 捕捉摄像头视频
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
if not ret:
break
cv2.imshow("Video Capture", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
# 使用场景
# OpenCV 广泛应用于计算机视觉任务,包括图像处理、视频分析、物体检测、人脸识别等。
# 它在科研、工业自动化、安全监控等领域都有广泛应用。Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.