杂项

Categories: Python

  1. enumerate将其组成一个索引序列,利用它可以同时获得索引和值

    for lineno, line in enumerate(self.lines, 1): 
  2. 迭代器切片

    for x in itertools.islice(c, 10, 20):
  3. 跳过可迭代对象的开始部分

    for line in dropwhile(lambda l: l.startswith('#'), f):
  4. 跳过所有#开头字符串

    lines = (line for line in f if not line.startswith('#'))
  5. 排列迭代

    for p in permutations(items, 2):
  6. 组合迭代

    for c in combinations(items, 2):
    
    for c in combinations_with_replacement(items, 2):
  7. 同时迭代多个序列

    for xv, yv in zip(x, y):
  8. 迭代多个序列,短的序列补0

    for xv, yv in zip_longest(x, y, fillvalue=0):
  9. 不同集合上元素的迭代

    for x in chain(a, b):
  10. 按顺序迭代已排序序列

    for c in heapq.merge(a, b):
  11. 迭代器代替while无限循环

    for chunk in iter(lambda : f.read(5), ''):
  12. 模拟普通文件

    s = io.StringIO('Hello\nworld\n'
  13. 固定大小记录的文件迭代

    records = iter(partial(f.read(), RECORD_SIZE), b'')
  14. 读取二进制数据到可变缓冲区中

    f.readinto(buf)
  15. 内存映射的二进制文件(mmap)

  16. 读取xml

    from xml.etree.ElementTree import parse
  17. 增量解析大型xml

    from xml.etree.ElementTree import iterparse
  18. 解析带命名空间的xml

  19. bisect维护列表顺序

  20. 让类支持比较操作

    from functools import total_ordering
    @total_ordering

See also