100 个必须掌握的 Python 数据类型操作技巧,建议收藏!

284 阅读4分钟

100 个必须掌握的 Python 数据类型操作技巧,建议收藏!

image.png

大家好我是花姐,这几天花时间整理出了一份超实用的100个Python操作各种数据类型的小技巧,涵盖了字符串、列表、元组、字典、集合、数字类型、布尔值、NoneType、日期、类型转换等日常开发中最常用的数据类型。


字符串(str)技巧

  1. str.upper() / str.lower():大小写转换
  2. str.title():标题化字符串(每个词首字母大写)
  3. str.strip() / lstrip() / rstrip():去空格
  4. str.replace('a', 'b'):字符串替换
  5. str.split(','):分割字符串为列表
  6. ','.join(list):列表拼接为字符串
  7. str.startswith('a') / endswith('z'):判断开头/结尾
  8. str.find('sub'):返回子串索引,不存在返回 -1
  9. str.count('a'):统计字符出现次数
  10. f-string 格式化:f"Hello {name}"

列表(list)技巧

  1. lst.append(x):追加元素
  2. lst.extend([1,2]):批量追加
  3. lst.insert(1, 'x'):指定位置插入
  4. lst.pop() / lst.pop(0):弹出元素
  5. lst.remove(x):移除第一个匹配元素
  6. lst.sort() / lst.sort(reverse=True):排序
  7. sorted(lst):返回新排序列表
  8. lst.reverse():原地反转
  9. [x for x in lst if x > 0]:列表推导式
  10. list(set(lst)):去重

元组(tuple)技巧

  1. t = (1,):单元素元组别忘了逗号
  2. tuple(lst):列表转元组
  3. a, b = (1, 2):元组拆包
  4. for i, val in enumerate(tpl):遍历带索引
  5. tpl.count(1) / tpl.index(1):计数、索引

字典(dict)技巧

  1. dict.get('key', 'default'):避免 key 错误
  2. dict.setdefault(k, v):如果没 key 就设值
  3. dict.update({'k': v}):批量更新
  4. dict.items():键值对遍历
  5. dict.keys() / dict.values():遍历 key / value
  6. {k: v for k, v in dict.items() if v > 0}:字典推导式
  7. del dict['key']:删除键
  8. fromkeys(['a', 'b'], 0):批量初始化
  9. Counter(lst):统计元素频次(from collections)
  10. json.loads() / json.dumps():字典和JSON互转

数字类型(int, float, complex

  1. round(3.1415, 2):保留2位小数
  2. abs(-9):绝对值
  3. divmod(7, 3):商和余数
  4. pow(2, 3):幂运算
  5. math.sqrt(9):开平方
  6. random.randint(1,10):生成随机整数
  7. float('inf') / -float('inf'):无穷大
  8. isinstance(x, int):类型检查
  9. decimal.Decimal('0.1'):高精度浮点数
  10. bin(10), oct(10), hex(10):进制转换

布尔类型(bool

  1. bool([]) / bool(''):空对象为 False
  2. all([True, True]) / any([False, True])
  3. not 逻辑取反
  4. 三元表达式:x if cond else y
  5. assert condition, "Error":断言调试用

NoneType

  1. if x is None: 检查是否为 None
  2. x = y or 'default':简洁的空值替代
  3. x = y if y is not None else z:显式替代
  4. filter(None, iterable):过滤掉 None 值
  5. my_dict.get('key') is not None:防止误判 0

集合(set)技巧

  1. set([1,2,2]):自动去重
  2. a & b:交集
  3. a | b:并集
  4. a - b:差集
  5. a ^ b:对称差
  6. a.issubset(b) / a.issuperset(b)
  7. set.add(x) / set.remove(x) / discard(x)
  8. set.pop():随机弹出一个元素
  9. frozenset():不可变集合
  10. len(set(x)) == len(x):快速判重

日期时间(datetime

  1. datetime.now():当前时间
  2. datetime.strptime('2023-01-01', '%Y-%m-%d'):字符串转日期
  3. datetime.strftime('%Y-%m-%d'):日期转字符串
  4. timedelta(days=7):时间差
  5. date.today():当前日期
  6. (end - start).days:天数差
  7. calendar.monthrange(2023, 2):获取月天数
  8. datetime.timestamp() / fromtimestamp()
  9. datetime.replace():替换时间字段
  10. pytz 时区处理(需额外安装)

类型转换技巧

  1. int('123') / float('3.14') / str(123)
  2. list('abc'):字符串转列表
  3. dict([('a', 1)]):列表转字典
  4. tuple([1,2,3]):列表转元组
  5. set([1,2,3]):列表转集合
  6. ord('A') / chr(65):字符与 ASCII 转换
  7. bytes('abc', 'utf-8') / .decode()
  8. eval("1+2"):字符串转表达式(⚠️慎用)
  9. repr(obj):对象的表示字符串
  10. isinstance(x, (list, tuple)):类型组检查

其他

  1. enumerate(lst):带索引的遍历
  2. zip(lst1, lst2):并行遍历
  3. map(str, lst):映射操作
  4. filter(lambda x: x>0, lst):条件筛选
  5. reduce(lambda x,y: x+y, lst):聚合计算(from functools)
  6. sorted(lst, key=lambda x: x[1]):按第二个元素排序
  7. collections.defaultdict(list):自动初始化
  8. copy.deepcopy(obj):深拷贝
  9. next(iter(lst)):安全地取第一个元素
  10. slice(1,5,2):切片对象

进阶一点的玩法

  1. namedtuple('Point', ['x', 'y'])
  2. itertools.combinations(lst, 2):组合
  3. chain.from_iterable():扁平化多层列表
  4. heapq.heappush() / heappop():堆操作
  5. globals() / locals():查看变量上下文

好啦,这就是今天为大家整理的 100 条 Python 数据类型操作技巧!是不是有不少技巧你以前没注意到,或者一直用错了?

如果你觉得这份清单有用,点个赞 ➕ 转发给身边的 Pythoner 一起进步!