news 2026/5/1 6:18:29

Python 常用函数大全

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
Python 常用函数大全

一、基础内置函数

1. 数据类型转换

int("123") # 123 float("3.14") # 3.14 str(123) # "123" bool(0) # False list("abc") # ['a', 'b', 'c'] tuple([1, 2, 3]) # (1, 2, 3) dict([('a', 1)]) # {'a': 1} set([1, 2, 2, 3]) # {1, 2, 3} chr(65) # 'A' ord('A') # 65 hex(255) # '0xff' oct(8) # '0o10' bin(5) # '0b101'

2. 数学运算

abs(-5) # 5 divmod(10, 3) # (3, 1) pow(2, 3) # 8 pow(2, 3, 5) # 3 (2³ mod 5) round(3.14159, 2) # 3.14 sum([1, 2, 3]) # 6 min([1, 2, 3]) # 1 max([1, 2, 3]) # 3

3. 输入输出

print("Hello", "World") # Hello World print("Value:", 10, sep=", ") # Value:, 10 input("Enter your name: ") # 获取用户输入

4. 序列操作

len([1, 2, 3]) # 3 range(5) # range(0, 5) list(range(1, 10, 2)) # [1, 3, 5, 7, 9] sorted([3, 1, 2]) # [1, 2, 3] sorted([3, 1, 2], reverse=True) # [3, 2, 1] reversed([1, 2, 3]) # 返回迭代器 list(reversed([1, 2, 3])) # [3, 2, 1] enumerate(['a', 'b', 'c']) # 返回(0,'a'), (1,'b'), (2,'c') list(enumerate(['a', 'b', 'c'], start=1)) # [(1,'a'), (2,'b'), (3,'c')] zip([1, 2, 3], ['a', 'b', 'c']) # 返回(1,'a'), (2,'b'), (3,'c')

5. 条件判断

all([True, True, False]) # False (所有为True) any([False, True, False]) # True (任一为True)

6. 对象和属性

type(123) # <class 'int'> isinstance(123, int) # True id([1, 2]) # 返回对象内存地址 callable(print) # True hasattr([1, 2], 'append') # True getattr([1, 2], 'append') # 返回append方法

二、字符串处理

字符串方法

s = "Hello World" s.upper() # "HELLO WORLD" s.lower() # "hello world" s.title() # "Hello World" s.capitalize() # "Hello world" s.startswith("Hello") # True s.endswith("World") # True s.find("World") # 6 s.index("World") # 6 s.count("l") # 3 s.replace("World", "Python") # "Hello Python" " hello ".strip() # "hello" " hello ".lstrip() # "hello " " hello ".rstrip() # " hello" "a,b,c".split(",") # ['a', 'b', 'c'] " ".join(['a', 'b']) # "a b" "hello".isalpha() # True "123".isdigit() # True "abc123".isalnum() # True " ".isspace() # True "hello".islower() # True "HELLO".isupper() # True

格式化字符串

name = "Alice" age = 25 f"My name is {name} and I'm {age} years old." # f-string "My name is {} and I'm {} years old.".format(name, age) # format "My name is %s and I'm %d years old." % (name, age) # %格式化

三、列表/数组操作

列表方法

lst = [1, 2, 3] lst.append(4) # [1, 2, 3, 4] lst.extend([5, 6]) # [1, 2, 3, 4, 5, 6] lst.insert(1, 1.5) # [1, 1.5, 2, 3, 4, 5, 6] lst.remove(1.5) # [1, 2, 3, 4, 5, 6] lst.pop() # 返回6, lst变为[1, 2, 3, 4, 5] lst.pop(0) # 返回1, lst变为[2, 3, 4, 5] lst.index(3) # 1 lst.count(2) # 1 lst.sort() # 升序排序 lst.sort(reverse=True) # 降序排序 lst.reverse() # 反转列表 lst.clear() # []

列表推导式

[i*2 for i in range(5)] # [0, 2, 4, 6, 8] [i for i in range(10) if i%2==0] # [0, 2, 4, 6, 8] [(x, y) for x in [1,2] for y in [3,4]] # [(1,3), (1,4), (2,3), (2,4)]

四、字典操作

字典方法

d = {'a': 1, 'b': 2} d.keys() # dict_keys(['a', 'b']) d.values() # dict_values([1, 2]) d.items() # dict_items([('a', 1), ('b', 2)]) d.get('a') # 1 d.get('c', 0) # 0 (c不存在,返回默认值0) d.setdefault('c', 3) # 设置c=3,c不存在时 d.pop('a') # 1,删除并返回 d.popitem() # 删除并返回最后一对 d.update({'c': 3}) # {'a': 1, 'b': 2, 'c': 3} d.clear() # {}

字典推导式

{x: x**2 for x in range(5)} # {0:0, 1:1, 2:4, 3:9, 4:16} {k.upper(): v*2 for k, v in {'a':1, 'b':2}.items()} # {'A':2, 'B':4}

五、集合操作

集合方法

s = {1, 2, 3} s.add(4) # {1, 2, 3, 4} s.remove(2) # {1, 3, 4} s.discard(5) # 删除5,不存在时不报错 s.pop() # 随机删除一个并返回 s.clear() # set() s.update([4, 5, 6]) # 添加多个元素

集合运算

a = {1, 2, 3} b = {3, 4, 5} a.union(b) # {1, 2, 3, 4, 5} a.intersection(b) # {3} a.difference(b) # {1, 2} a.symmetric_difference(b) # {1, 2, 4, 5}

六、数学函数(math模块)

import math math.ceil(3.2) # 4 (向上取整) math.floor(3.8) # 3 (向下取整) math.trunc(3.8) # 3 (截断) math.fabs(-3.14) # 3.14 (绝对值,返回浮点) math.sqrt(16) # 4.0 math.pow(2, 3) # 8.0 math.exp(1) # 2.718... (e^1) math.log(10) # 2.302... (自然对数) math.log10(100) # 2.0 math.sin(math.pi/2) # 1.0 math.cos(0) # 1.0 math.degrees(math.pi) # 180.0 math.radians(180) # 3.14159... math.gcd(12, 8) # 4 (最大公约数) math.lcm(12, 8) # 24 (最小公倍数,Python 3.9+) math.comb(5, 2) # 10 (组合数) math.perm(5, 2) # 20 (排列数)

七、随机数(random模块)

import random random.random() # [0.0, 1.0) 的随机浮点数 random.uniform(1, 10) # [1, 10) 的随机浮点数 random.randint(1, 10) # [1, 10] 的随机整数 random.randrange(1, 10, 2) # 1,3,5,7,9 中随机 random.choice(['a', 'b', 'c']) # 随机选择元素 random.choices(['a', 'b', 'c'], k=2) # 有放回抽样 random.sample([1,2,3,4,5], k=3) # 无放回抽样 random.shuffle([1,2,3,4]) # 打乱列表

八、日期时间(datetime模块)

from datetime import datetime, date, time, timedelta # 当前时间 now = datetime.now() today = date.today() # 创建日期时间 dt = datetime(2023, 12, 25, 10, 30, 0) d = date(2023, 12, 25) t = time(10, 30, 0) # 格式化 now.strftime("%Y-%m-%d %H:%M:%S") # 日期转字符串 datetime.strptime("2023-12-25", "%Y-%m-%d") # 字符串转日期 # 时间运算 now + timedelta(days=1) # 加1天 now - timedelta(hours=2) # 减2小时 # 获取属性 now.year, now.month, now.day now.hour, now.minute, now.second now.weekday() # 0-6 周一为0

九、文件操作

# 读取文件 with open('file.txt', 'r', encoding='utf-8') as f: content = f.read() # 读取全部 lines = f.readlines() # 读取所有行 line = f.readline() # 读取一行 for line in f: # 逐行读取 print(line.strip()) # 写入文件 with open('file.txt', 'w') as f: f.write("Hello\n") f.writelines(["Line1\n", "Line2\n"]) # 追加模式 with open('file.txt', 'a') as f: f.write("Appended text\n")

十、高级函数

迭代器工具

# map: 对每个元素应用函数 list(map(lambda x: x**2, [1, 2, 3])) # [1, 4, 9] # filter: 过滤元素 list(filter(lambda x: x > 0, [-2, -1, 0, 1, 2])) # [1, 2] # reduce: 累积运算 from functools import reduce reduce(lambda x, y: x + y, [1, 2, 3, 4]) # 10 # zip: 并行迭代 names = ['Alice', 'Bob'] scores = [90, 85] dict(zip(names, scores)) # {'Alice': 90, 'Bob': 85}

lambda表达式

add = lambda x, y: x + y add(3, 4) # 7 # 常用场景 sorted([('a', 3), ('b', 1), ('c', 2)], key=lambda x: x[1]) # 按第二个元素排序

十一、装饰器

# 基本装饰器 def my_decorator(func): def wrapper(*args, **kwargs): print("Before function") result = func(*args, **kwargs) print("After function") return result return wrapper @my_decorator def say_hello(): print("Hello!") # 带参数的装饰器 def repeat(times): def decorator(func): def wrapper(*args, **kwargs): for _ in range(times): result = func(*args, **kwargs) return result return wrapper return decorator @repeat(times=3) def greet(name): print(f"Hello {name}")

十二、类和对象

class Person: # 类属性 species = "Human" def __init__(self, name, age): # 实例属性 self.name = name self.age = age # 实例方法 def introduce(self): return f"I'm {self.name}, {self.age} years old." # 类方法 @classmethod def from_birth_year(cls, name, birth_year): age = datetime.now().year - birth_year return cls(name, age) # 静态方法 @staticmethod def is_adult(age): return age >= 18 # 使用 p = Person("Alice", 25) p.introduce() # "I'm Alice, 25 years old." Person.is_adult(20) # True

十三、错误处理

# 基本try-except try: x = 1 / 0 except ZeroDivisionError as e: print(f"Error: {e}") except (TypeError, ValueError) as e: print(f"Other error: {e}") except Exception as e: print(f"Unexpected error: {e}") else: print("No error occurred") finally: print("This always runs") # 抛出异常 if x < 0: raise ValueError("x must be non-negative") # 自定义异常 class MyError(Exception): pass

十四、上下文管理器

# 创建上下文管理器 from contextlib import contextmanager @contextmanager def my_context(): print("Entering context") yield print("Exiting context") with my_context(): print("Inside context") # 处理文件自动关闭 class FileManager: def __init__(self, filename, mode): self.filename = filename self.mode = mode def __enter__(self): self.file = open(self.filename, self.mode) return self.file def __exit__(self, exc_type, exc_val, exc_tb): self.file.close() with FileManager('test.txt', 'w') as f: f.write("Hello")

十五、性能分析

# 计时 import time start = time.time() # 执行代码 end = time.time() print(f"Time: {end - start} seconds") # 更精确计时 import timeit timeit.timeit('"-".join(str(n) for n in range(100))', number=10000) # 性能分析 import cProfile cProfile.run('your_function()')

十六、实用工具函数

# enumerate: 带索引的迭代 for i, value in enumerate(['a', 'b', 'c']): print(i, value) # 0 a, 1 b, 2 c # zip: 并行迭代多个序列 for name, score in zip(['Alice', 'Bob'], [90, 85]): print(name, score) # reversed: 反向迭代 for i in reversed(range(5)): print(i) # 4, 3, 2, 1, 0 # sorted: 排序 sorted([3, 1, 2]) # [1, 2, 3] sorted([3, 1, 2], reverse=True) # [3, 2, 1] # any/all: 条件判断 any(x > 0 for x in [-1, 0, 1]) # True all(x > 0 for x in [1, 2, 3]) # True
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/4/21 23:17:17

48、Windows文件关联深度解析与定制指南

Windows文件关联深度解析与定制指南 1. 注册表HKCR概述 在Windows系统中,注册表的大部分文件关联和类注册内容存储在HKCR中。Windows XP和Windows Server 2003通过HKCR将不同类型的文件与能够打开、编辑和打印它们的程序相关联,同时注册不同的程序类以便创建对象。 对HKCR…

作者头像 李华
网站建设 2026/5/1 0:20:39

50、Windows 网络设置注册表项详解

Windows 网络设置注册表项详解 在Windows系统中,注册表是一个重要的系统数据库,它存储了系统和应用程序的各种配置信息。通过调整注册表中的某些值,可以对系统的网络设置进行优化。以下将详细介绍几个关键的网络设置注册表项及其作用。 1. Users Users 是一个 REG_DWOR…

作者头像 李华
网站建设 2026/5/1 6:03:11

38、Windows部署:注册表配置与应答文件使用全攻略

Windows部署:注册表配置与应答文件使用全攻略 1. 部署准备:创建分发文件夹 在Windows部署中,有多种方式可以创建用于Sysprep、远程安装服务或无人值守安装的i386分发文件夹。可以使用Setup Manager来完成这一任务,它位于Windows CD的\Support\Tools文件夹下的Deploy.cab文…

作者头像 李华
网站建设 2026/4/23 14:01:14

56、Windows 系统每台计算机的设置详解

Windows 系统每台计算机的设置详解 在 Windows 系统中,有许多注册表设置可以影响系统的各种功能和行为。下面将详细介绍一些重要的注册表设置及其作用。 1. Internet Explorer 相关设置 在注册表中, HKLM\SOFTWARE\Clients\Mail\Outlook Express\shell 子键定义了用户在…

作者头像 李华
网站建设 2026/5/1 6:08:40

MateChat实战指南:5分钟构建智能对话界面的高效工具

还在为AI对话界面开发而烦恼吗&#xff1f;&#x1f914; 每次都要从零开始搭建聊天组件&#xff0c;调试样式&#xff0c;处理复杂的交互逻辑&#xff1f;现在&#xff0c;有了MateChat这个前端智能化场景解决方案UI库&#xff0c;你可以在几分钟内构建出专业级的智能对话界面…

作者头像 李华
网站建设 2026/5/1 5:59:17

FaceFusion在广告创意中的实际应用案例分享

FaceFusion在广告创意中的实际应用案例分享在一场护肤品牌的线上推广活动中&#xff0c;超过百万用户上传了自己的自拍照&#xff0c;不是为了晒美颜&#xff0c;而是想看看“三年后使用了这款产品&#xff0c;我的脸会变成什么样”。这不是科幻电影的桥段&#xff0c;而是真实…

作者头像 李华