《使用Python常用函数说明》
Python作为一门简洁易学且功能强大的编程语言,凭借其丰富的内置函数和标准库函数,为开发者提供了高效解决各类问题的工具。本文将系统梳理Python中常用的核心函数,涵盖数据类型处理、数学运算、字符串操作、文件管理、时间日期处理、列表与字典操作等场景,通过代码示例和实际应用场景说明其用法,帮助读者快速掌握Python函数的核心应用。
一、数学运算相关函数
Python内置的数学函数通过`math`模块提供,支持基础运算、三角函数、对数运算等。以下是常用函数的详细说明:
1. 基础运算函数
import math
# 绝对值
print(math.fabs(-3.14)) # 输出: 3.14
# 四舍五入
print(round(3.14159, 2)) # 输出: 3.14
# 取整(向下)
print(math.floor(3.9)) # 输出: 3
# 取整(向上)
print(math.ceil(3.1)) # 输出: 4
`math.fabs()`用于获取浮点数的绝对值,而`abs()`可处理整数和浮点数。`round()`的第二个参数指定小数位数,`math.floor()`和`math.ceil()`分别实现向下和向上取整。
2. 高级数学函数
# 平方根
print(math.sqrt(16)) # 输出: 4.0
# 幂运算
print(math.pow(2, 3)) # 输出: 8.0
# 对数运算
print(math.log(100, 10)) # 输出: 2.0(以10为底的对数)
print(math.log2(8)) # 输出: 3.0(以2为底的对数)
print(math.log1p(1)) # 输出: 0.693...(计算log(1+x))
`math.sqrt()`计算平方根,`math.pow(x,y)`等价于`x**y`。对数函数中,`math.log()`默认以自然对数e为底,可通过第二个参数指定底数;`math.log2()`和`math.log10()`分别计算以2和10为底的对数。
3. 三角函数
angle = math.pi / 4 # 45度对应的弧度值
# 正弦、余弦、正切
print(math.sin(angle)) # 输出: 0.707...
print(math.cos(angle)) # 输出: 0.707...
print(math.tan(angle)) # 输出: 1.0
# 弧度与角度转换
print(math.degrees(math.pi)) # 输出: 180.0(弧度转角度)
print(math.radians(90)) # 输出: 1.570...(角度转弧度)
三角函数参数需为弧度值,可通过`math.radians()`将角度转换为弧度。`math.pi`为圆周率常量,约等于3.14159。
二、字符串操作函数
字符串是Python中最常用的数据类型之一,内置函数提供了丰富的字符串处理方法。
1. 基础操作函数
s = "Hello, Python"
# 长度计算
print(len(s)) # 输出: 13
# 大小写转换
print(s.upper()) # 输出: HELLO, PYTHON
print(s.lower()) # 输出: hello, python
print(s.title()) # 输出: Hello, Python(每个单词首字母大写)
# 去除空白字符
s2 = " hello "
print(s2.strip()) # 输出: hello(去除首尾空格)
print(s2.lstrip()) # 输出: hello (去除左侧空格)
print(s2.rstrip()) # 输出: hello(去除右侧空格)
`len()`函数返回字符串长度,`strip()`系列方法用于去除空白字符,常用于数据清洗场景。
2. 查找与替换
s = "apple banana apple"
# 查找子串
print(s.find("banana")) # 输出: 6(首次出现位置,未找到返回-1)
print(s.count("apple")) # 输出: 2(统计出现次数)
# 替换子串
print(s.replace("apple", "orange")) # 输出: orange banana orange
# 分割字符串
print(s.split()) # 输出: ['apple', 'banana', 'apple'](默认按空格分割)
`find()`与`index()`的区别在于,后者在未找到时会抛出异常。`replace()`可指定替换次数,如`s.replace("a", "X", 2)`仅替换前两个"a"。
3. 格式化输出
name = "Alice"
age = 25
# f-string(Python 3.6+)
print(f"My name is {name}, I'm {age} years old.")
# format方法
print("My name is {}, I'm {} years old.".format(name, age))
print("My name is {0}, I'm {1} years old.".format(name, age))
print("My name is {name}, I'm {age} years old.".format(name=name, age=age))
# 百分比格式化(旧式)
print("My name is %s, I'm %d years old." % (name, age))
f-string是Python 3.6引入的高效格式化方式,支持表达式嵌入(如`f"{age*2}"`)。`format()`方法更灵活,适合复杂场景。
三、列表操作函数
列表是Python中最常用的可变序列,内置函数支持增删改查等操作。
1. 列表创建与访问
nums = [1, 2, 3, 4, 5]
# 索引访问
print(nums[0]) # 输出: 1
print(nums[-1]) # 输出: 5(负索引从-1开始)
# 切片操作
print(nums[1:3]) # 输出: [2, 3](左闭右开区间)
print(nums[:3]) # 输出: [1, 2, 3](从开头到索引2)
print(nums[3:]) # 输出: [4, 5](从索引3到末尾)
print(nums[::2]) # 输出: [1, 3, 5](步长为2)
切片操作支持三个参数:`start:stop:step`,省略时分别默认为0、列表长度、1。
2. 列表修改函数
nums = [1, 2, 3]
# 追加元素
nums.append(4) # 输出: [1, 2, 3, 4]
nums.extend([5,6]) # 输出: [1, 2, 3, 4, 5, 6]
# 插入元素
nums.insert(1, "x") # 输出: [1, 'x', 2, 3, 4, 5, 6]
# 删除元素
nums.pop() # 删除并返回末尾元素
nums.pop(0) # 删除并返回索引0的元素
nums.remove("x") # 删除第一个值为"x"的元素
# 排序与反转
nums.sort() # 升序排序
nums.sort(reverse=True) # 降序排序
nums.reverse() # 反转列表
`extend()`与`+`的区别在于,前者直接修改原列表,后者生成新列表。`sort()`是列表方法,而`sorted()`是内置函数,可对任意可迭代对象排序。
3. 列表推导式
# 生成平方数列表
squares = [x**2 for x in range(5)] # 输出: [0, 1, 4, 9, 16]
# 带条件的列表推导式
even_squares = [x**2 for x in range(10) if x % 2 == 0] # 输出: [0, 4, 16, 36, 64]
# 嵌套列表推导式
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row] # 输出: [1, 2, 3, 4, 5, 6, 7, 8, 9]
列表推导式提供简洁的创建列表方式,性能优于普通循环。嵌套推导式可处理多维数据结构。
四、字典操作函数
字典是Python中唯一的映射类型,通过键值对存储数据。
1. 字典创建与访问
person = {"name": "Alice", "age": 25, "city": "New York"}
# 访问值
print(person["name"]) # 输出: Alice
print(person.get("age")) # 输出: 25
print(person.get("country", "Unknown")) # 输出: Unknown(键不存在时返回默认值)
# 检查键是否存在
print("name" in person) # 输出: True
print(person.keys()) # 输出: dict_keys(['name', 'age', 'city'])
print(person.values()) # 输出: dict_values(['Alice', 25, 'New York'])
print(person.items()) # 输出: dict_items([('name', 'Alice'), ...])
使用`get()`方法可避免`KeyError`异常,适合不确定键是否存在的场景。
2. 字典修改函数
person = {"name": "Alice", "age": 25}
# 添加/修改键值对
person["city"] = "New York" # 添加新键
person["age"] = 26 # 修改现有键
# 删除键值对
del person["name"] # 删除指定键
popped_value = person.pop("age") # 删除并返回值
popped_value = person.pop("country", "N/A") # 键不存在时返回默认值
# 合并字典(Python 3.9+)
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
merged = dict1 | dict2 # 输出: {'a': 1, 'b': 3, 'c': 4}
`update()`方法可用于合并字典,如`dict1.update(dict2)`。Python 3.9+引入的`|`运算符更简洁。
3. 字典推导式
# 创建数字平方字典
squares = {x: x**2 for x in range(5)} # 输出: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# 带条件的字典推导式
even_squares = {x: x**2 for x in range(10) if x % 2 == 0} # 输出: {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
# 转换字典键值
words = {"apple": 5, "banana": 3}
inverted = {value: key for key, value in words.items()} # 输出: {5: 'apple', 3: 'banana'}
字典推导式可快速实现数据转换,常用于数据清洗和格式转换场景。
五、文件操作函数
Python通过内置函数和`open()`方法提供文件读写能力。
1. 文件读写基础
# 写入文件
with open("test.txt", "w") as f:
f.write("Hello, Python!\nSecond line.")
# 读取文件(全部内容)
with open("test.txt", "r") as f:
content = f.read()
print(content) # 输出: Hello, Python!\nSecond line.
# 逐行读取
with open("test.txt", "r") as f:
for line in f:
print(line.strip()) # 输出: Hello, Python! 然后 Second line.
# 读取所有行到列表
with open("test.txt", "r") as f:
lines = f.readlines()
print(lines) # 输出: ['Hello, Python!\n', 'Second line.']
`with`语句可自动管理文件资源,确保文件正确关闭。模式参数包括`"r"`(读)、`"w"`(写)、`"a"`(追加)、`"b"`(二进制)等。
2. 文件路径处理
import os
# 获取当前工作目录
print(os.getcwd()) # 输出: /current/directory/path
# 拼接路径
path = os.path.join("folder", "subfolder", "file.txt") # 输出: folder/subfolder/file.txt
# 分解路径
print(os.path.split(path)) # 输出: ('folder/subfolder', 'file.txt')
print(os.path.splitext(path)) # 输出: ('folder/subfolder/file', '.txt')
# 检查路径是否存在
print(os.path.exists(path)) # 输出: False(除非文件存在)
`os.path`模块提供跨平台的路径操作函数,避免直接使用字符串拼接导致的路径错误。
3. JSON文件处理
import json
# 写入JSON文件
data = {"name": "Alice", "age": 25, "city": "New York"}
with open("data.json", "w") as f:
json.dump(data, f)
# 读取JSON文件
with open("data.json", "r") as f:
loaded_data = json.load(f)
print(loaded_data) # 输出: {'name': 'Alice', 'age': 25, 'city': 'New York'}
# 字符串与JSON转换
json_str = '{"name": "Bob", "age": 30}'
python_dict = json.loads(json_str)
new_json_str = json.dumps(python_dict, indent=4) # 格式化输出
`json`模块支持Python对象与JSON字符串的相互转换,`indent`参数可控制输出格式。
六、时间日期处理函数
Python通过`datetime`模块提供时间日期处理功能。
1. 获取当前时间
from datetime import datetime
now = datetime.now()
print(now) # 输出: 2023-05-15 14:30:45.123456
# 获取时间各部分
print(now.year) # 输出: 2023
print(now.month) # 输出: 5
print(now.day) # 输出: 15
print(now.hour) # 输出: 14
print(now.minute) # 输出: 30
print(now.second) # 输出: 45
`datetime.now()`返回包含当前日期和时间的`datetime`对象。
2. 时间格式化
now = datetime.now()
# 格式化为字符串
formatted = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted) # 输出: 2023-05-15 14:30:45
# 字符串解析为datetime对象
date_str = "2023-05-15"
parsed_date = datetime.strptime(date_str, "%Y-%m-%d")
print(parsed_date) # 输出: 2023-05-15 00:00:00
常用格式化符号:`%Y`(年)、`%m`(月)、`%d`(日)、`%H`(小时)、`%M`(分钟)、`%S`(秒)。
3. 时间差计算
from datetime import datetime, timedelta
now = datetime.now()
future = now + timedelta(days=7) # 7天后
past = now - timedelta(hours=12) # 12小时前
print(future - now) # 输出: 7 days, 0:00:00
print(now - past) # 输出: 12:00:00
`timedelta`对象支持天、秒、微秒等单位的加减运算。
七、其他常用函数
1. 输入输出函数
# 输入函数
name = input("Enter your name: ") # 用户输入后按回车
print(f"Hello, {name}!")
# 打印函数(重定向)
import sys
original_stdout = sys.stdout # 保存原始输出
with open("output.txt", "w") as f:
sys.stdout = f # 重定向输出到文件
print("This goes to file.")
sys.stdout = original_stdout # 恢复原始输出
`input()`函数返回字符串类型,需手动转换数字等类型。重定向输出可用于日志记录等场景。
2. 随机数生成
import random
# 生成随机整数
print(random.randint(1, 10)) # 输出: 1-10之间的随机整数
# 从序列中随机选择
items = ["apple", "banana", "cherry"]
print(random.choice(items)) # 输出: 随机选择一个元素
# 打乱序列顺序
random.shuffle(items)
print(items) # 输出: 打乱后的列表
# 生成随机浮点数
print(random.random()) # 输出: 0.0-1.0之间的随机浮点数
print(random.uniform(1.5, 3.5)) # 输出: 1.5-3.5之间的随机浮点数
`random`模块的种子可通过`random.seed()`设置,用于可重复的随机序列生成。
3. 异常处理函数
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print("No exception occurred.")
finally:
print("This always executes.")
# 自定义异常
class MyError(Exception):
pass
try:
raise MyError("Something went wrong")
except MyError as e:
print(f"Caught an error: {e}")
`try-except`块捕获异常,`else`在无异常时执行,`finally`无论是否发生异常都会执行。
八、函数式编程工具
Python提供`map()`、`filter()`、`reduce()`等函数式编程工具。
1. map函数
nums = [1, 2, 3, 4]
# 将每个元素平方
squared = list(map(lambda x: x**2, nums)) # 输出: [1, 4, 9, 16]
# 字符串列表转大写
words = ["apple", "banana"]
upper_words = list(map(str.upper, words)) # 输出: ['APPLE', 'BANANA']
`map()`将函数应用于可迭代对象的每个元素,返回迭代器,需用`list()`等转换为列表。
2. filter函数
nums = [1, 2, 3, 4, 5, 6]
# 筛选偶数
evens = list(filter(lambda x: x % 2 == 0, nums)) # 输出: [2, 4, 6]
# 筛选非空字符串
words = ["", "a", "", "b", "c"]
non_empty = list(filter(None, words)) # 输出: ['a', 'b', 'c']
`filter()`保留使函数返回`True`的元素,`None`作为函数参数时筛选非假值。
3. reduce函数
from functools import reduce
nums = [1, 2, 3, 4]
# 计算乘积
product = reduce(lambda x, y: x * y, nums) # 输出: 24
# 查找最大值
max_num = reduce(lambda a, b: a if a > b else b, nums) # 输出: 4
`reduce()`对序列元素进行累积计算,需从`functools`模块导入。
九、总结
本文系统梳理了Python中常用的内置函数和标准库函数,涵盖数学运算、字符串处理、列表与字典操作、文件管理、时间日期处理、输入输出、随机数生成、异常处理及函数式编程工具。掌握这些函数可显著提升开发效率,减少重复代码。建议读者通过实际项目练习,深入理解各函数的应用场景和参数细节。
关键词:Python函数、数学运算、字符串操作、列表推导式、字典操作、文件读写、JSON处理、时间日期、随机数生成、异常处理、函数式编程
简介:本文详细介绍Python中常用的内置函数和标准库函数,包括数学运算、字符串处理、列表与字典操作、文件管理、时间日期处理等核心场景,通过代码示例说明用法,帮助开发者快速掌握Python函数的高效应用。