当前位置: 代码网 > it编程>前端脚本>Python > Python基础入门之len、abs、sum等内置函数使用汇总

Python基础入门之len、abs、sum等内置函数使用汇总

2026年07月26日 Python 我要评论
一、开篇:python的内置函数python自带70多个内置函数(built-in functions),——不需要import,随时可用,覆盖了类型转换、数学计算、序列操作、

一、开篇:python的内置函数

python自带70多个内置函数(built-in functions),——不需要import,随时可用,覆盖了类型转换、数学计算、序列操作、对象信息等方方面面。

你已经在日常编程中大量使用它们了:

# 这些你不用import就能用:
print(len([1, 2, 3]))      # 3
print(abs(-5))              # 5
print(sum([1, 2, 3]))      # 6
print(type("hello"))        # <class 'str'>
print(int("42"))            # 42
print(range(10))            # range(0, 10)
print(isinstance(5, int))   # true

这篇文章,我们对python内置函数做一个系统性的梳理——按类别整理,了解每个函数的用途和典型用法。这不只是一份"速查表",更是帮你建立python全局视野的指南。

二、数学相关内置函数

2.1 基本数学运算

# abs(x) —— 绝对值
print(abs(-10))        # 10
print(abs(3.14))       # 3.14
print(abs(-3 + 4j))    # 5.0 —— 复数的模

# round(number, ndigits) —— 四舍五入
print(round(3.14159, 2))   # 3.14
print(round(3.14159))      # 3(不指定精度,保留到整数)
print(round(2.5))          # 2 —— ⚠️ 注意:银行家舍入!

# pow(base, exp, mod) —— 幂运算(可带模)
print(pow(2, 10))          # 1024
print(pow(2, 10, 1000))    # 24 —— 等价于 (2**10) % 1000,但更高效

# divmod(a, b) —— 同时返回商和余数
quotient, remainder = divmod(17, 5)
print(f"17 ÷ 5 = {quotient} 余 {remainder}")  # 17 ÷ 5 = 3 余 2
# 常用于:分页计算、时间换算
total_minutes = 137
hours, minutes = divmod(total_minutes, 60)
print(f"{hours}小时{minutes}分钟")  # 2小时17分钟

2.2 聚合函数

# sum(iterable, start) —— 求和
print(sum([1, 2, 3, 4, 5]))        # 15
print(sum([1, 2, 3], 10))          # 16(从10开始加)
# 性能提示:sum()用c实现,比for循环快得多

# min(iterable) / min(a, b, c, ...) —— 最小值
print(min([5, 2, 8, 1, 9]))        # 1
print(min(5, 2, 8, 1, 9))          # 1
print(min("python", "java", "c"))  # 'c' —— 按字母顺序

# min也支持key参数
words = ["python", "java", "c", "go", "rust"]
print(min(words, key=len))          # 'c' —— 最短的

# max(iterable) —— 最大值
print(max([5, 2, 8, 1, 9]))        # 9
print(max(words, key=len))          # 'python' —— 最长的

# 实用组合
scores = [85, 92, 78, 95, 88]
avg = sum(scores) / len(scores)
print(f"平均分: {avg:.1f}, 最高: {max(scores)}, 最低: {min(scores)}")

三、类型转换内置函数

3.1 数值类型转换

# int(x, base) —— 转整数
print(int(3.14))           # 3
print(int("42"))           # 42
print(int("1010", 2))      # 10 —— 二进制字符串转十进制
print(int("ff", 16))       # 255 —— 十六进制
print(int("0xff", 16))     # 255 —— 0x前缀也能处理

# float(x) —— 转浮点数
print(float(42))           # 42.0
print(float("3.14"))       # 3.14
print(float("inf"))        # inf —— 无穷大
print(float("nan"))        # nan —— 非数字

# complex(real, imag) —— 转复数
print(complex(3, 4))       # (3+4j)
print(complex("3+4j"))     # (3+4j)

# bool(x) —— 转布尔值
print(bool(1))             # true
print(bool(0))             # false
print(bool([]))            # false —— 空列表是假值
print(bool([1, 2]))        # true
print(bool("hello"))       # true
print(bool(""))            # false

3.2 序列类型转换

# list(iterable) —— 转列表
print(list("hello"))       # ['h', 'e', 'l', 'l', 'o']
print(list(range(5)))      # [0, 1, 2, 3, 4]
print(list((1, 2, 3)))    # [1, 2, 3]

# tuple(iterable) —— 转元组
print(tuple([1, 2, 3]))   # (1, 2, 3)

# set(iterable) —— 转集合(自动去重)
print(set([1, 2, 2, 3, 3, 3]))  # {1, 2, 3}

# dict(**kwargs) 或 dict(mapping) —— 创建字典
print(dict(name="张三", age=25))      # {'name': '张三', 'age': 25}
print(dict([("a", 1), ("b", 2)]))    # {'a': 1, 'b': 2}

# frozenset(iterable) —— 不可变集合
fs = frozenset([1, 2, 3])
# fs.add(4)  # attributeerror! 不可修改

# str(object) —— 转字符串
print(str(42))             # "42"
print(str([1, 2, 3]))     # "[1, 2, 3]"
print(str(none))           # "none"

# bytes(source) —— 创建字节对象
print(bytes([72, 101, 108, 108, 111]))  # b'hello'
print(bytes("hello", "utf-8"))           # b'hello'

# bytearray(source) —— 可变的字节数组
ba = bytearray(b"hello")
ba[0] = 104  # 'h'的ascii码
print(ba)  # bytearray(b'hello')

四、序列操作内置函数

4.1 信息获取

# len(s) —— 获取长度
print(len("python"))           # 6
print(len([1, 2, 3, 4, 5]))  # 5
print(len({"a": 1, "b": 2}))  # 2

# ⚠️ len()是o(1)操作——python内部记录了长度

4.2 创建和转换序列

# range(start, stop, step) —— 创建整数序列
print(list(range(5)))              # [0, 1, 2, 3, 4]
print(list(range(2, 8)))           # [2, 3, 4, 5, 6, 7]
print(list(range(0, 10, 2)))       # [0, 2, 4, 6, 8]
print(list(range(10, 0, -1)))      # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

# enumerate(iterable, start) —— 带索引的迭代
fruits = ["苹果", "香蕉", "橙子"]
for i, fruit in enumerate(fruits, 1):
    print(f"{i}. {fruit}")
# 1. 苹果
# 2. 香蕉
# 3. 橙子

# zip(*iterables) —— 并行迭代
names = ["张三", "李四", "王五"]
scores = [85, 92, 78]
for name, score in zip(names, scores):
    print(f"{name}: {score}")
# 张三: 85
# 李四: 92
# 王五: 78

# 矩阵转置(zip的经典应用)
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transposed = list(zip(*matrix))
print(transposed)  # [(1, 4, 7), (2, 5, 8), (3, 6, 9)]

# reversed(sequence) —— 反向迭代
print(list(reversed([1, 2, 3, 4])))  # [4, 3, 2, 1]
print("".join(reversed("hello")))    # 'olleh'

# sorted(iterable, key, reverse) —— 排序
print(sorted([3, 1, 4, 1, 5]))      # [1, 1, 3, 4, 5]

# slice(start, stop, step) —— 创建切片对象
s = slice(1, 5, 2)
print([0, 1, 2, 3, 4, 5, 6, 7, 8, 9][s])  # [1, 3]

# filter(function, iterable) —— 过滤
# map(function, iterable) —— 映射

五、对象信息内置函数

5.1 类型和身份检查

# type(object) —— 获取类型
print(type(42))              # <class 'int'>
print(type("hello"))         # <class 'str'>
print(type([1, 2, 3]))      # <class 'list'>

# isinstance(object, classinfo) —— 检查是否为某类型
print(isinstance(42, int))              # true
print(isinstance(42, (int, float)))     # true —— 可以是多个类型之一
print(isinstance("hello", str))         # true
print(isinstance([1, 2], (list, tuple))) # true

# issubclass(class, classinfo) —— 检查子类关系
class animal: pass
class dog(animal): pass
print(issubclass(dog, animal))  # true
print(issubclass(dog, object))  # true

# id(object) —— 获取对象的内存地址
a = [1, 2, 3]
b = a
print(id(a))   # 例如: 140234567890
print(id(b))   # 相同——同一个对象
print(id([1, 2, 3]))  # 不同——新创建的对象

# hash(object) —— 获取哈希值
print(hash("hello"))     # 某个整数
print(hash((1, 2, 3)))   # 某个整数
# hash([1, 2, 3])  # typeerror! 列表不可哈希

5.2 属性和能力检查

# dir(object) —— 列出对象的所有属性和方法
print(dir("hello"))  # 列出字符串的所有方法
print(dir([]))       # 列出列表的所有方法

# hasattr(obj, name) —— 检查是否有某属性
print(hasattr("hello", "upper"))     # true
print(hasattr("hello", "foo"))       # false

# getattr(obj, name, default) —— 获取属性
print(getattr("hello", "upper"))     # <built-in method upper>
print(getattr("hello", "foo", none)) # none —— 不存在返回默认值

# setattr(obj, name, value) —— 设置属性
class config: pass
cfg = config()
setattr(cfg, "debug", true)
print(cfg.debug)  # true

# callable(object) —— 检查是否为可调用对象
print(callable(print))     # true —— 函数可调用
print(callable(lambda: 1)) # true —— lambda可调用
print(callable(42))        # false —— 数字不可调用
print(callable("hello"))   # false —— 字符串不可调用

六、i/o和字符串相关

6.1 输入输出

# print(*objects, sep, end, file, flush)
print("hello", "world", sep=", ", end="!\n")
# hello, world!

# 打印到文件
# with open("output.txt", "w") as f:
#     print("日志信息", file=f)

# input(prompt) —— 获取用户输入
# name = input("请输入你的名字: ")
# age = int(input("请输入你的年龄: "))

# open(file, mode, ...) —— 打开文件
# with open("data.txt", "r", encoding="utf-8") as f:
#     content = f.read()

6.2 字符编码和格式化

# ord(c) —— 字符转unicode码点
print(ord('a'))    # 65
print(ord('中'))   # 20013
print(ord('😀'))   # 128512

# chr(i) —— unicode码点转字符
print(chr(65))     # 'a'
print(chr(20013))  # '中'
print(chr(128512)) # '😀'

# repr(object) —— 获取对象的表示形式
print(repr("hello\nworld"))  # 'hello\nworld'

# ascii(object) —— ascii表示(非ascii字符转义)
print(ascii("hello 世界"))  # 'hello 世界'

# format(value, format_spec) —— 格式化
print(format(255, 'x'))     # 'ff' —— 十六进制
print(format(255, '#x'))    # '0xff'
print(format(3.14159, '.2f'))  # '3.14'

# bin(x), oct(x), hex(x) —— 进制转换
print(bin(10))   # '0b1010'
print(oct(10))   # '0o12'
print(hex(255))  # '0xff'

七、函数式编程内置函数

# iter(iterable) —— 获取迭代器
it = iter([1, 2, 3])
print(next(it))  # 1
print(next(it))  # 2
print(next(it))  # 3

# next(iterator, default) —— 获取下一个元素
it = iter([1])
print(next(it, "default"))  # 1
print(next(it, "default"))  # 'default' —— 迭代器耗尽

# any(iterable) —— 任一为true
print(any([false, false, true]))   # true
print(any([0, "", none, false]))   # false

# all(iterable) —— 全部为true
print(all([true, true, true]))     # true
print(all([true, false, true]))    # false

八、最常用的内置函数top 10

根据使用频率排名

  • print() —— 输出
  • len() —— 获取长度
  • type() —— 查看类型
  • int() / str() / float() —— 类型转换
  • range() —— 生成序列
  • list() / dict() / tuple() / set() —— 创建容器
  • input() —— 获取输入
  • enumerate() / zip() —— 序列操作
  • isinstance() —— 类型检查
  • sorted() / min() / max() / sum() —— 聚合

熟练掌握这10类函数,能覆盖日常编程90%的需求

九、总结

python的70+内置函数是语言设计哲学"电池已包含"(batteries included)的体现。它们覆盖了数学计算、类型转换、序列操作、对象信息、i/o、编码转换等方方面面。

使用建议:

  1. 优先使用内置函数——c实现,速度快,bug少
  2. 了解但不死记——知道有哪些就行,需要时查
  3. 善用内置函数组合——sum(map(int, data)) 之类的链式调用

以上就是python基础入门之len、abs、sum等内置函数使用汇总的详细内容,更多关于python内置函数的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com