社区后台开发 → 浏览:帖子主题
* 帖子主题:Python 中的数据类型操作
pojin (ID: 1)
等级: 骑士
积分:49
发帖:0
来自:保密
注册:2026-03-20 07:11:48
造访:-
[ 第 1 楼 ] 回复
Python 中的数据类型操作,涵盖了字符串、列表、元组、字典、集合、数字类型、布尔值、NoneType、日期、类型转换等日常开发中最常用的数据类型:

1. 字符串 (str)

大小写转换:str.upper(), str.lower(), str.title()

空白处理:str.strip(), str.lstrip(), str.rstrip()

查找与替换:str.replace('a', 'b'), str.find('sub'), str.count('a')

分割与拼接:str.split(','), ','.join(list)

首尾判断:str.startswith('a'), str.endswith('z')

格式化:f"Hello {name}" (f-string)

2. 列表 (list)

增:lst.append(x), lst.extend([1](@ref)[2](@ref), lst.insert(1, 'x')

删:lst.pop(), lst.pop(0), lst.remove(x)

排序与反转:lst.sort(), lst.sort(reverse=True), sorted(lst), lst.reverse()

推导式:[x for x in lst if x > 0]

去重:list(set(lst))

3. 元组 (tuple)

创建注意: 单元素元组需加逗号 t = (1,)

转换:tuple(lst) (列表转元组)

拆包:a, b = (1, 2)

遍历:for i, val in enumerate(tpl) (带索引)

查询:tpl.count(1), tpl.index(1)

4. 字典 (dict)

安全访问:dict.get('key', 'default'), dict.setdefault(k, v)

更新:dict.update({'k': v})

遍历:dict.items() (键值对), dict.keys(), dict.values()

推导式:{k: v for k, v in dict.items() if v > 0}

删除:del dict['key']

初始化:dict.fromkeys(['a', 'b'], 0)

统计:Counter(lst) (需 from collections import Counter)

JSON 互转:json.loads(), json.dumps() (需 import json)

5. 数字类型 (int, float, complex)

数值运算:round(3.1415, 2), abs(-9), divmod(7, 3), pow(2, 3), math.sqrt(9) (需 import math)

随机数:random.randint(1,10) (需 import random)

特殊值:float('inf'), -float('inf') (无穷大)

类型检查:isinstance(x, int)

高精度:decimal.Decimal('0.1') (需 from decimal import Decimal)

进制转换:bin(10), oct(10), hex(10)

6. 布尔类型 (bool)

真值判断:bool([]), bool('') (空对象为 False)

逻辑运算:all([True, True]), any([False, True]), not

条件表达式:x if cond else y (三元表达式)

断言:assert condition, "Error" (调试用)

7. NoneType

检查:if x is None: (使用 is 而非 ==)

空值替代:x = y or 'default', x = y if y is not None else z

过滤:filter(None, iterable) (过滤掉 None 值)

字典检查:my_dict.get('key') is not None (区分 None 和 0/False)

8. 集合 (set)

核心特性:set([1](@ref)[2](@ref)[2](@ref) (自动去重)

集合运算:a & b (交集), a | b (并集), a - b (差集), a ^ b (对称差)

关系判断:a.issubset(b), a.issuperset(b)

元素操作:set.add(x), set.remove(x), set.discard(x) (安全删除), set.pop() (随机弹出)

不可变集合:frozenset()

快速判重:len(set(x)) == len(x)

9. 日期时间 (datetime)

获取时间:datetime.now(), date.today()

格式转换:datetime.strptime('2023-01-01', '%Y-%m-%d') (字符串转日期), datetime.strftime('%Y-%m-%d') (日期转字符串)

时间差:timedelta(days=7), (end - start).days (天数差)

时间戳:datetime.timestamp(), datetime.fromtimestamp()

修改字段:datetime.replace()

月信息:calendar.monthrange(2023, 2) (需 import calendar)

时区:pytz (需额外安装)

10. 类型转换

基础转换:int('123'), float('3.14'), str(123), list('abc'), dict([('a', 1)]), tuple([1](@ref)[2](@ref)[3](@ref), set([1](@ref)[2](@ref)[3](@ref)

字符编码:ord('A'), chr(65)

字节处理:bytes('abc', 'utf-8'), .decode()

对象表示:repr(obj)

类型检查:isinstance(x, (list, tuple)) (可检查多种类型)

慎用:eval("1+2") (字符串转表达式,有安全风险)

11. 其他实用工具

迭代增强:enumerate(lst) (带索引遍历), zip(lst1, lst2) (并行遍历)

函数式编程:map(str, lst) (映射), filter(lambda x: x>0, lst) (过滤), reduce(lambda x,y: x+y, lst) (聚合,需 from functools import reduce)

高级排序:sorted(lst, key=lambda x: x[1](@ref) (按自定义键排序)

默认字典:collections.defaultdict(list) (自动初始化值)

拷贝:copy.deepcopy(obj) (深拷贝)

安全取首元素:next(iter(lst))

切片对象:slice(1,5,2)

12. 进阶玩法

命名元组:collections.namedtuple('Point', ['x', 'y'])

组合:itertools.combinations(lst, 2)

扁平化:itertools.chain.from_iterable() (处理多层列表)

堆操作:heapq.heappush(), heapq.heappop() (需 import heapq)

变量上下文:globals(), locals()

2026-03-23 22:18:12 IP:已设置保密
快速回复主题
账号/密码
用户: 没有注册?密码:
评论内容