Python 数据类型与内置函数详解
目录
1. 数据类型概览
Python 是动态类型语言,变量不需要声明类型,解释器会自动推断。
类型分类
查看类型
type(42) # <class 'int'>type(3.14) # <class 'float'>type("hello") # <class 'str'>type([1, 2, 3]) # <class 'list'>isinstance(42, int) # Trueisinstance(42, (int, float)) # True
2. 数值类型
整数 (int)
# 整数没有大小限制(受内存限制)a = 42b = -10c = 0# 不同进制decimal = 100# 十进制binary = 0b1010# 二进制: 10octal = 0o755# 八进制: 493hexadecimal = 0xFF# 十六进制: 255# 大整数big_num = 2 ** 100print(big_num) # 1267650600228229401496703205376# 整数运算10 + 3# 1310 - 3# 710 * 3# 3010 / 3# 3.333... (返回 float)10 // 3# 3 (整除)10 % 3# 1 (取余)10 ** 3# 1000 (幂)
浮点数 (float)
# 浮点数x = 3.14y = -0.5z = 1.0# 科学计数法a = 1.5e10# 15000000000.0b = 2.5e-3# 0.0025# 精度问题(浮点数运算不精确)0.1 + 0.2# 0.30000000000000004round(0.1 + 0.2, 1) # 0.3# 特殊值float('inf') # 正无穷float('-inf') # 负无穷float('nan') # 非数字
复数 (complex)
z = 3 + 4jz.real # 3.0 (实部)z.imag # 4.0 (虚部)z.conjugate() # (3-4j) (共轭复数)abs(z) # 5.0 (模)
math 模块常用函数
import mathmath.pi # 3.141592653589793math.e # 2.718281828459045math.sqrt(16) # 4.0math.ceil(3.2) # 4 (向上取整)math.floor(3.8) # 3 (向下取整)math.trunc(3.8) # 3 (截断)math.factorial(5) # 120 (阶乘)math.pow(2, 10) # 1024.0math.log(100, 10) # 2.0 (对数)math.sin(math.pi/2) # 1.0math.cos(0) # 1.0
3. 字符串 (str)
创建字符串
s1 = '单引号's2 = "双引号"s3 = '''多行字符串'''s4 = """也可以多行"""# 转义字符"\n"# 换行"\t"# 制表符"\\"# 反斜杠"\""# 双引号r"C:\Users"# 原始字符串,不转义
字符串操作
text = "Hello, Python World!"# 长度len(text) # 20# 索引与切片text[0] # 'H'text[-1] # '!'text[7:13] # 'Python'text[:5] # 'Hello'text[7:] # 'Python World!'text[::-1] # '!dlroW nohtyP ,olleH'# 拼接与重复"Hello" + " " + "World"# 'Hello World'"Ha" * 3# 'HaHaHa'
常用方法
text = " Hello, Python World! "# 大小写转换text.upper() # ' HELLO, PYTHON WORLD! 'text.lower() # ' hello, python world! 'text.title() # ' Hello, Python World! 'text.swapcase() # 大小写互换text.capitalize() # 首字母大写# 去除空白text.strip() # 'Hello, Python World!'text.lstrip() # 去除左侧空白text.rstrip() # 去除右侧空白# 查找与替换text.find("Python") # 9 (返回索引,找不到返回 -1)text.index("Python") # 9 (找不到抛出异常)text.count("o") # 2text.replace("Python", "Java")text.startswith("Hello") # Truetext.endswith("!") # True# 分割与连接"apple,banana,orange".split(",") # ['apple', 'banana', 'orange']"line1\nline2\nline3".splitlines() # ['line1', 'line2', 'line3']"-".join(["2024", "01", "15"]) # '2024-01-15'# 判断方法"abc".isalpha() # True (纯字母)"123".isdigit() # True (纯数字)"abc123".isalnum() # True (字母或数字)" ".isspace() # True (纯空白)"Hello".istitle() # True (标题格式)"hello".islower() # True (全小写)"WORLD".isupper() # True (全大写)# 填充与对齐"42".zfill(5) # '00042'"hello".ljust(10, "-") # 'hello-----'"hello".rjust(10, "-") # '-----hello'"hello".center(11, "*") # '***hello***'
字符串格式化
name = "Alice"age = 30score = 95.5# f-string (Python 3.6+, 推荐)f"我叫{name},今年{age}岁,得分{score}"f"明年我{age + 1}岁"f"{score:.1f}"# '95.5' (保留1位小数)f"{score:010.2f}"# '0000095.50' (宽度10,补0)f"{name:>10}"# ' Alice' (右对齐)f"{name:<10}"# 'Alice ' (左对齐)f"{name:^10}"# ' Alice ' (居中)f"{1000000:,}"# '1,000,000' (千位分隔符)f"{0.85:.1%}"# '85.0%' (百分比)f"{255:x}"# 'ff' (十六进制)f"{255:b}"# '11111111' (二进制)# format() 方法"我叫{},今年{}岁".format(name, age)"我叫{0},{0}今年{1}岁".format(name, age)"我叫{name},今年{age}岁".format(name="Alice", age=30)# % 格式化 (旧式)"我叫%s,今年%d岁" % (name, age)"得分%.2f" % score
4. 列表 (list)
创建列表
# 创建nums = [1, 2, 3, 4, 5]mixed = [1, "hello", True, 3.14, None]nested = [[1, 2], [3, 4], [5, 6]]empty = []from_range = list(range(5)) # [0, 1, 2, 3, 4]# 列表推导式squares = [x**2for x in range(10)]evens = [x for x in range(20) if x % 2 == 0]matrix = [[i*j for j in range(3)] for i in range(3)]
访问与切片
fruits = ["apple", "banana", "cherry", "date", "elderberry"]fruits[0] # 'apple'fruits[-1] # 'elderberry'fruits[1:3] # ['banana', 'cherry']fruits[:3] # ['apple', 'banana', 'cherry']fruits[2:] # ['cherry', 'date', 'elderberry']fruits[::2] # ['apple', 'cherry', 'elderberry']fruits[::-1] # 反转列表
修改列表
nums = [1, 2, 3, 4, 5]# 修改元素nums[0] = 10# [10, 2, 3, 4, 5]# 切片赋值nums[1:3] = [20, 30] # [10, 20, 30, 4, 5]# 添加元素nums.append(6) # 末尾添加nums.insert(0, 0) # 指定位置插入nums.extend([7, 8]) # 扩展多个元素nums += [9, 10] # 等价于 extend# 删除元素nums.pop() # 删除并返回最后一个nums.pop(0) # 删除并返回指定位置nums.remove(20) # 删除第一个匹配值del nums[2:4] # 切片删除nums.clear() # 清空列表
列表方法
nums = [3, 1, 4, 1, 5, 9, 2, 6]nums.index(4) # 2 (第一次出现的索引)nums.count(1) # 2 (出现次数)nums.sort() # 原地排序nums.sort(reverse=True) # 降序sorted(nums) # 返回新列表nums.reverse() # 原地反转reversed(nums) # 返回迭代器nums.copy() # 浅拷贝
列表操作
# 拼接[1, 2] + [3, 4] # [1, 2, 3, 4]# 重复[0] * 5# [0, 0, 0, 0, 0]# 判断3in [1, 2, 3] # True5notin [1, 2, 3] # True# 长度、最大、最小len([1, 2, 3]) # 3max([1, 2, 3]) # 3min([1, 2, 3]) # 1sum([1, 2, 3]) # 6# 解包a, b, c = [1, 2, 3]first, *rest = [1, 2, 3, 4, 5] # first=1, rest=[2, 3, 4, 5]
5. 元组 (tuple)
创建元组
# 创建point = (3, 4)colors = ("red", "green", "blue")single = (42,) # 单元素元组需要逗号empty = ()# 省略括号coords = 3, 4, 5# 转换tuple([1, 2, 3]) # (1, 2, 3)tuple("hello") # ('h', 'e', 'l', 'l', 'o')
元组操作
t = (1, 2, 3, 2, 1)t[0] # 1t.count(1) # 2t.index(2) # 1len(t) # 52in t # True# 元组不可修改# t[0] = 10 # TypeError!
解包
# 基本解包x, y = (3, 4)# 嵌套解包(a, b), (c, d) = (1, 2), (3, 4)# 星号解包first, *middle, last = (1, 2, 3, 4, 5)# first=1, middle=[2, 3, 4], last=5# 交换变量a, b = b, a
命名元组
from collections import namedtuplePoint = namedtuple('Point', ['x', 'y'])p = Point(3, 4)p.x # 3p.y # 4p[0] # 3
6. 字典 (dict)
创建字典
# 创建person = {"name": "Alice", "age": 30, "city": "Beijing"}empty = {}from_pairs = dict([("name", "Alice"), ("age", 30)])from_kwargs = dict(name="Alice", age=30)# 字典推导式squares = {x: x**2for x in range(5)}# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}# 默认值字典keys = ["a", "b", "c"]d = dict.fromkeys(keys, 0) # {'a': 0, 'b': 0, 'c': 0}
访问与修改
person = {"name": "Alice", "age": 30}# 访问person["name"] # 'Alice'person.get("name") # 'Alice'person.get("phone", "N/A") # 'N/A' (默认值)# 修改person["age"] = 31person["phone"] = "123456"# 添加新键# 批量更新person.update({"age": 32, "email": "alice@example.com"})# 删除del person["phone"]person.pop("age") # 删除并返回值person.popitem() # 删除并返回最后一个键值对person.clear() # 清空
字典方法
person = {"name": "Alice", "age": 30, "city": "Beijing"}person.keys() # dict_keys(['name', 'age', 'city'])person.values() # dict_values(['Alice', 30, 'Beijing'])person.items() # dict_items([('name', 'Alice'), ...])# 遍历for key in person: print(key)for value in person.values(): print(value)for key, value in person.items(): print(f"{key}: {value}")# 安全获取person.setdefault("phone", "N/A") # 不存在则添加并返回默认值
字典合并 (Python 3.9+)
d1 = {"a": 1, "b": 2}d2 = {"b": 3, "c": 4}d1 | d2 # {'a': 1, 'b': 3, 'c': 4}d1 |= d2 # 原地更新
嵌套字典
students = {"Alice": {"age": 20, "grade": "A"},"Bob": {"age": 22, "grade": "B"},}students["Alice"]["age"] # 20
7. 集合 (set)
创建集合
# 创建fruits = {"apple", "banana", "orange"}from_list = set([1, 2, 3, 3, 4]) # {1, 2, 3, 4}empty = set() # 注意: {} 是空字典# 集合推导式squares = {x**2for x in range(5)}
集合操作
s = {1, 2, 3}# 添加与删除s.add(4)s.update([5, 6])s.remove(3) # 不存在抛出异常s.discard(3) # 不存在不报错s.pop() # 随机删除并返回s.clear()# 长度与判断len(s) # 长度2in s # True
集合运算
a = {1, 2, 3, 4}b = {3, 4, 5, 6}# 并集a | ba.union(b)# 交集a & ba.intersection(b)# 差集a - ba.difference(b)# 对称差集a ^ ba.symmetric_difference(b)# 子集与超集{1, 2}.issubset(a) # Truea.issuperset({1, 2}) # True{1, 2}.isdisjoint({3, 4}) # True (无交集)
冻结集合 (frozenset)
# 不可变集合fs = frozenset([1, 2, 3])# fs.add(4) # AttributeError!# 可作为字典键或集合元素d = {frozenset({1, 2}): "value"}
8. 布尔值 (bool)
布尔运算
TrueandFalse# FalseTrueorFalse# TruenotTrue# False# 短路求值Falseand print("不会执行")Trueor print("不会执行")
真值测试
# 假值bool(False) # Falsebool(None) # Falsebool(0) # Falsebool(0.0) # Falsebool("") # Falsebool([]) # Falsebool({}) # Falsebool(set()) # False# 其他所有值都为 Truebool(1) # Truebool("hello") # Truebool([1, 2]) # True
比较运算符
1 == 1# True1 != 2# True1 < 2# True1 > 0# True1 <= 1# True1 >= 2# False# 链式比较1 < 2 < 3# True1 == 1 == 1# True# 身份比较a = [1, 2, 3]b = ac = [1, 2, 3]a is b # True (同一对象)a is c # False (不同对象)a == c # True (值相等)
9. NoneType
# None 表示空值x = None# 判断x isNone# Truex isnotNone# False# 函数默认返回值deffunc():passresult = func() # None# 默认参数defgreet(name=None):if name isNone: name = "Guest"returnf"Hello, {name}!"
10. 类型转换
内置类型转换函数
# 数值转换int("123") # 123int("1010", 2) # 10 (二进制转十进制)int(3.9) # 3 (截断)float("3.14") # 3.14float("1e5") # 100000.0complex("3+4j") # (3+4j)# 字符串转换str(123) # '123'str(3.14) # '3.14'str([1, 2, 3]) # '[1, 2, 3]'repr("hello") # "'hello'" (带引号)# 序列转换list("hello") # ['h', 'e', 'l', 'l', 'o']list((1, 2, 3)) # [1, 2, 3]tuple([1, 2, 3]) # (1, 2, 3)set([1, 2, 2, 3]) # {1, 2, 3}# 字典转换dict([("a", 1), ("b", 2)]) # {'a': 1, 'b': 2}dict(a=1, b=2) # {'a': 1, 'b': 2}# 其他bool(1) # Truebool("") # Falsechr(65) # 'A' (ASCII 转字符)ord('A') # 65 (字符转 ASCII)hex(255) # '0xff'oct(255) # '0o377'bin(255) # '0b11111111'
11. 内置函数大全
数学运算
abs(-10) # 10 (绝对值)divmod(10, 3) # (3, 1) (商, 余数)pow(2, 10) # 1024 (幂)pow(2, 10, 1000) # 24 (幂后取模)round(3.14159, 2) # 3.14max(1, 2, 3) # 3max([1, 2, 3]) # 3min(1, 2, 3) # 1sum([1, 2, 3]) # 6sum([1, 2, 3], 10) # 16 (带初始值)
类型相关
type(42) # <class 'int'>isinstance(42, int) # Trueissubclass(bool, int) # Trueid(x) # 对象内存地址hash("hello") # 哈希值
序列操作
# 长度len("hello") # 5len([1, 2, 3]) # 3# 范围range(5) # 0, 1, 2, 3, 4range(2, 10, 2) # 2, 4, 6, 8# 枚举for i, v in enumerate(["a", "b", "c"]): print(i, v) # 0 a, 1 b, 2 c# 压缩for x, y in zip([1, 2], ["a", "b"]): print(x, y) # 1 a, 2 b# 映射list(map(str, [1, 2, 3])) # ['1', '2', '3']list(map(lambda x: x*2, [1, 2, 3])) # [2, 4, 6]# 过滤list(filter(bool, [0, 1, "", "hello"])) # [1, 'hello']# 排序sorted([3, 1, 2]) # [1, 2, 3]sorted("cba") # ['a', 'b', 'c']sorted([1, -2, 3], key=abs) # [1, -2, 3]sorted([3, 1, 2], reverse=True) # [3, 2, 1]# 反转reversed([1, 2, 3]) # 迭代器list(reversed([1, 2, 3])) # [3, 2, 1]# 切片slice(1, 5, 2) # 切片对象
迭代器相关
# 迭代器iter([1, 2, 3]) # 创建迭代器next(iter([1, 2])) # 1# 全部消费all([True, True]) # Trueall([True, False]) # Falseany([False, False]) # Falseany([False, True]) # True# 累加import functoolsfunctools.reduce(lambda x, y: x + y, [1, 2, 3]) # 6
输入输出
# 输入name = input("请输入名字: ")# 输出print("Hello")print("a", "b", sep="-") # a-bprint("Hello", end="!") # 不换行print("Error", file=sys.stderr)# 格式化输出format(3.14159, ".2f") # '3.14'format(255, "x") # 'ff'format(42, "05d") # '00042'
对象相关
# 属性操作classObj: x = 1obj = Obj()getattr(obj, 'x') # 1setattr(obj, 'y', 2) # 设置属性hasattr(obj, 'x') # Truedelattr(obj, 'y') # 删除属性# 方向dir([1, 2, 3]) # 列出所有属性和方法# 可调用callable(print) # Truecallable(42) # False# 编译与执行code = compile("print('hello')", "<string>", "exec")exec(code) # helloeval("1 + 2") # 3
类与对象
# 创建类classPerson:def__init__(self, name): self.name = name# 实例化p = Person("Alice")# 类相关isinstance(p, Person) # Trueissubclass(Person, object) # Truevars(p) # {'name': 'Alice'}
其他内置函数
# 帮助help(print)# 绝对路径__file__# 全局/局部变量globals()locals()# 静态方法/类方法classMath: @staticmethoddefadd(a, b):return a + b @classmethoddeffrom_string(cls, s):return cls()# 属性classTemperature:def__init__(self, celsius): self._celsius = celsius @propertydeffahrenheit(self):return self._celsius * 9/5 + 32
12. 实战练习
练习 1: 数据类型判断
defanalyze_type(value):"""分析值的类型并返回信息""" info = {"value": value,"type": type(value).__name__,"is_mutable": False,"length": None, }# 判断可变性if isinstance(value, (list, dict, set)): info["is_mutable"] = True# 获取长度try: info["length"] = len(value)except TypeError:passreturn info# 测试print(analyze_type([1, 2, 3]))print(analyze_type("hello"))print(analyze_type(42))
练习 2: 列表去重并保持顺序
defunique_keep_order(lst):"""列表去重并保持原有顺序""" seen = set() result = []for item in lst:if item notin seen: seen.add(item) result.append(item)return result# 测试print(unique_keep_order([3, 1, 2, 3, 1, 4, 2]))# 输出: [3, 1, 2, 4]
练习 3: 字典合并工具
defmerge_dicts(*dicts):"""合并多个字典,后面的覆盖前面的""" result = {}for d in dicts: result.update(d)return result# 测试d1 = {"a": 1, "b": 2}d2 = {"b": 3, "c": 4}d3 = {"d": 5}print(merge_dicts(d1, d2, d3))# 输出: {'a': 1, 'b': 3, 'c': 4, 'd': 5}
练习 4: 字符串统计
defcount_chars(text):"""统计字符串中各类字符数量""" stats = {"letters": 0,"digits": 0,"spaces": 0,"others": 0, }for char in text:if char.isalpha(): stats["letters"] += 1elif char.isdigit(): stats["digits"] += 1elif char.isspace(): stats["spaces"] += 1else: stats["others"] += 1return stats# 测试text = "Hello World! 123"print(count_chars(text))# 输出: {'letters': 10, 'digits': 3, 'spaces': 2, 'others': 1}
练习 5: 嵌套数据处理
defflatten(nested):"""展平嵌套列表""" result = []for item in nested:if isinstance(item, list): result.extend(flatten(item))else: result.append(item)return result# 测试nested = [1, [2, 3], [4, [5, 6]], 7]print(flatten(nested))# 输出: [1, 2, 3, 4, 5, 6, 7]
速查表
常用类型方法速查
| |
|---|
| upper, lower, strip, split, join, replace, find, format |
| append, extend, insert, pop, remove, sort, reverse, index, count |
| keys, values, items, get, pop, update, setdefault |
| add, remove, discard, union, intersection, difference |
| |
常用内置函数速查
| |
|---|
| |
| |
| |
| str/int/float/list/dict/set | |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
掌握数据类型和内置函数是 Python 编程的基础,建议多练习、多查阅官方文档。