本平台致力于为Python开发者提供全面、准确、实用的函数查询服务,覆盖Python内置函数、标准库模块及主流第三方库函数。无论您是初学者、进阶开发者还是资深工程师,都能在此找到所需知识,快速解决开发中的实际问题。
我们深知,函数是Python编程的基石。正确理解并灵活运用函数,是写出高效、可维护代码的关键。因此,我们不仅提供函数的参数说明与返回值定义,更注重呈现真实场景中的使用范例、常见陷阱与最佳实践,帮助您真正掌握函数的使用精髓。
页面采用响应式设计,适配手机、平板、桌面等多种设备,所有内容均以语义化HTML5结构组织,确保搜索引擎可抓取、可索引,提升SEO友好性。所有导航均为锚点跳转,无需页面刷新,访问流畅无阻。
我们坚持“内容为王”原则,拒绝空洞堆砌,每项函数说明均经过严格校验与实例验证,确保准确性与实用性并重。所有示例代码均经Python 3.8+环境实测通过,兼容性有保障。
欢迎收藏本页,作为您日常开发的“函数工具箱”。我们持续更新,敬请关注。
Python内置函数是语言核心的一部分,无需导入任何模块即可直接使用。它们是Python简洁、强大特性的集中体现。掌握内置函数,是高效编程的第一步。
all(iterable):当iterable中所有元素均为True(或为空)时返回True,否则返回False。常用于条件校验,如检查列表中是否所有元素满足某条件。
# 示例:检查所有数字是否为正数
nums = [1, 2, 3, 4]
print(all(n > 0 for n in nums)) # True
nums = [1, -1, 3]
print(all(n > 0 for n in nums)) # False
any(iterable):当iterable中至少有一个元素为True时返回True,否则返回False。与all()互补,适合用于存在性判断。
# 示例:检查是否存在负数
nums = [1, 2, 3]
print(any(n < 0 for n in nums)) # False
nums = [1, -1, 3]
print(any(n < 0 for n in nums)) # True
enumerate(iterable, start=0):返回一个枚举对象,将可迭代对象组合为索引-值对。避免手动维护计数器,是遍历列表的首选方式。
# 示例:打印带索引的列表项
fruits = ['苹果', '香蕉', '橙子']
for idx, fruit in enumerate(fruits):
print(f"{idx+1}. {fruit}")
# 输出:
# 1. 苹果
# 2. 香蕉
# 3. 橙子
filter(function, iterable):过滤序列,返回使function(item)为True的元素组成的迭代器。常用于数据清洗。
# 示例:筛选大于10的数
data = [5, 12, 3, 18, 7]
filtered = list(filter(lambda x: x > 10, data))
print(filtered) # [12, 18]
map(function, *iterables):对多个可迭代对象的每个元素应用函数,返回结果迭代器。是函数式编程的核心工具。
# 示例:将字符串列表转换为整数
str_nums = ['1', '2', '3']
int_nums = list(map(int, str_nums))
print(int_nums) # [1, 2, 3]
zip(*iterables):将多个可迭代对象“打包”为元组迭代器。常用于并行遍历。
# 示例:并行遍历姓名与年龄
names = ['张三', '李四', '王五']
ages = [25, 30, 28]
for name, age in zip(names, ages):
print(f"{name}今年{age}岁")
# 输出:
# 张三今年25岁
# 李四今年30岁
# 王五今年28岁
sorted(iterable, *, key=None, reverse=False):返回新的已排序列表,不改变原对象。支持自定义排序规则。
# 示例:按字典值排序
scores = {'数学': 95, '英语': 88, '物理': 92}
sorted_scores = sorted(scores.items(), key=lambda x: x[1], reverse=True)
print(sorted_scores) # [('数学', 95), ('物理', 92), ('英语', 88)]
bool(x):将值转换为布尔类型。Python中False、0、空字符串、空容器等被视为False,其余为True。
int(x, base=10):将数字或字符串转换为整数。支持指定进制(2-36),如int('1A', 16)返回26。
str(object=''):将对象转换为字符串。__str__方法定义了对象的字符串表示。
list(x):将可迭代对象转换为列表。是构建列表最通用的方式之一。
lambda:创建匿名函数。语法简洁,适合简单逻辑的内联函数定义。
# 示例:定义一个返回平方的匿名函数
square = lambda x: x ** 2
print(square(5)) # 25
open(file, mode='r', ...):打开文件并返回文件对象。参数mode决定打开方式(如'r'读、'w'写、'a'追加、'b'二进制)。
# 示例:读取文本文件
with open('data.txt', 'r', encoding='utf-8') as f:
content = f.read()
print(content[:100]) # 打印前100字符
with语句:上下文管理器,确保资源(如文件)在使用后正确释放,避免资源泄漏。
Python标准库是“自带电池”理念的体现,提供大量实用模块。掌握常用标准库,可避免重复造轮子,大幅提升开发效率。
datetime模块:处理日期与时间的核心模块。
datetime.datetime.now():获取当前本地时间datetime.timedelta(days=7):时间差对象,支持加减运算datetime.strftime(format):格式化时间为字符串datetime.strptime(string, format):解析字符串为时间对象from datetime import datetime, timedelta
now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S")) # 2025-04-05 14:30:22
one_week_later = now + timedelta(days=7)
print(one_week_later.strftime("%Y-%m-%d")) # 2025-04-12
os & pathlib模块:跨平台文件系统操作。
os.path.join():安全拼接路径os.listdir(path):列出目录内容Path.cwd():获取当前工作目录(pathlib)Path.glob('*.txt'):通配符查找文件from pathlib import Path
# 创建路径对象
docs = Path('documents')
# 检查是否存在
if not docs.exists():
docs.mkdir()
# 遍历所有.txt文件
for file in docs.glob('*.txt'):
print(file.name)
json模块:处理JSON数据,常用于API通信与配置存储。
json.dumps(obj):Python对象转JSON字符串json.loads(string):JSON字符串转Python对象json.dump(obj, file):直接写入文件json.load(file):直接从文件读取import json
data = {"name": "张三", "age": 28}
json_str = json.dumps(data, ensure_ascii=False)
print(json_str) # {"name": "张三", "age": 28}
parsed = json.loads(json_str)
print(parsed['name']) # 张三
re模块:强大的文本处理工具。
re.search(pattern, string):搜索第一个匹配re.findall(pattern, string):返回所有匹配项列表re.sub(pattern, repl, string):替换匹配项re.compile(pattern):预编译模式,提升重复使用性能import re
text = "Python 3.10发布于2021年10月"
# 提取所有数字
numbers = re.findall(r'\d+', text)
print(numbers) # ['3', '10', '2021', '10']
# 提取年份(4位数字)
year = re.search(r'\d{4}', text).group()
print(year) # 2021
configparser模块:解析INI格式配置文件。
[database]
host = localhost
port = 3306
user = admin
import configparser
config = configparser.ConfigParser()
config.read('config.ini')
host = config['database']['host']
port = config.getint('database', 'port')
logging模块:灵活的日志系统,支持多级别、多输出。
import logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
logging.info("应用启动")
logging.error("数据库连接失败")
第三方库极大扩展了Python的应用边界。以下为高频使用库的核心函数整理,助您快速上手。
numpy是科学计算的基石,提供高性能数组操作。
np.array(list):创建数组np.zeros(shape) / np.ones(shape):全零/全一数组np.arange(start, stop, step):等差数列np.random.rand(*shape):[0,1)随机数组arr.reshape(new_shape):重塑数组形状import numpy as np
# 创建二维数组
arr = np.array([[1, 2], [3, 4]])
print(arr.shape) # (2, 2)
# 生成3x3随机矩阵
rand_mat = np.random.rand(3, 3)
print(rand_mat)
pandas是数据处理的利器,提供DataFrame结构。
pd.DataFrame(data):创建DataFramedf.head(n):查看前n行df['col'].value_counts():统计列值频次df.groupby('col').mean():分组聚合df.to_csv('file.csv'):导出为CSVimport pandas as pd
# 创建DataFrame
data = {'姓名': ['张三', '李四', '王五'],
'分数': [85, 92, 78]}
df = pd.DataFrame(data)
print(df)
# 分数排序
df_sorted = df.sort_values('分数', ascending=False)
print(df_sorted)
requests是HTTP客户端库,简单易用。
requests.get(url, params=...) :GET请求requests.post(url, data=...) :POST请求response.status_code:状态码response.json():解析JSON响应response.headers:响应头import requests
# 获取GitHub用户信息
resp = requests.get('https://api.github.com/users/octocat')
print(resp.status_code) # 200
user_data = resp.json()
print(user_data['login']) # octocat
flask是轻量级Web框架,适合快速构建API。
Flask(__name__):创建应用实例@app.route('/path'):注册路由request.args.get('key'):获取GET参数request.json:获取JSON请求体jsonify(data):返回JSON响应from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/hello', methods=['GET'])
def hello():
name = request.args.get('name', '世界')
return jsonify(message=f'你好,{name}!')
if __name__ == '__main__':
app.run(debug=True)
pytest是现代化测试框架,语法简洁、功能强大。
def test_xxx()::测试函数命名规范assert condition:断言pytest.mark.skip(reason="..."):跳过测试fixture:测试夹具,提供前置/后置操作import pytest
def add(a, b):
return a + b
def test_add():
assert add(2, 3) == 5
assert add(-1, 1) == 0
处理用户评论数据,过滤无效信息、标准化格式。
import re
def clean_comment(text):
# 去除HTML标签
text = re.sub(r'<[^>]+>', '', text)
# 去除URL
text = re.sub(r'http[s]?://\S+', '', text)
# 去除多余空白
text = re.sub(r'\s+', ' ', text).strip()
return text
comments = ["太好了![赞]", "https://example.com 很棒", " 噢! "]
cleaned = [clean_comment(c) for c in comments]
print(cleaned) # ['太好了![赞]', '', '噢!']
从天气API获取数据并提取关键信息。
import requests
import json
# 示例响应(实际需替换为真实API)
response = {
"city": "北京",
"weather": "晴",
"temp": 25,
"humidity": 60
}
# 提取并格式化输出
info = f"{response['city']}:{response['weather']},气温{response['temp']}℃,湿度{response['humidity']}%"
print(info) # 北京:晴,气温25℃,湿度60%
批量创建项目目录结构。
from pathlib import Path
project = Path('my_project')
dirs = ['src', 'tests', 'docs', 'assets/images']
for d in dirs:
(project / d).mkdir(parents=True, exist_ok=True)
print(list(project.iterdir())) # [PosixPath('my_project/src'), ...]
分析销售数据,计算各产品总销量。
import pandas as pd
# 模拟数据
data = {
'产品': ['A', 'B', 'A', 'C', 'B'],
'销量': [100, 150, 200, 80, 120]
}
df = pd.DataFrame(data)
# 分组求和
summary = df.groupby('产品')['销量'].sum().reset_index()
print(summary)
# 输出:
# 产品 销量
# 0 A 300
# 1 B 270
# 2 C 80
*args和**kwargs是什么?A:用于接收不定数量的参数:
*args:接收任意数量的位置参数,打包为元组**kwargs:接收任意数量的关键字参数,打包为字典def func(a, *args, **kwargs):
print(f"a={a}, args={args}, kwargs={kwargs}")
func(1, 2, 3, x=4, y=5)
# 输出:a=1, args=(2, 3), kwargs={'x': 4, 'y': 5}
A:在参数定义时指定默认值:
def greet(name, greeting="你好"):
print(f"{greeting},{name}!")
greet("小明") # 你好,小明!
greet("小红", "早上好") # 早上好,小红!
注意:默认参数值应在定义时确定,避免使用可变对象(如列表)作为默认值,以防状态共享。
A:会!列表是可变对象,函数内修改会影响原对象:
def add_item(lst):
lst.append('new')
items = ['apple']
add_item(items)
print(items) # ['apple', 'new']
如需避免,应传入副本:add_item(items.copy())或add_item(items[:])。
A:使用yield而非return,返回迭代器,节省内存:
def count_up_to(max):
count = 1
while count <= max:
yield count
count += 1
counter = count_up_to(3)
print(next(counter)) # 1
print(list(counter)) # [2, 3]
适合处理大数据流,避免一次性加载全部数据。