30 Seconds of Code: Python

30 Seconds of Code: Python

本文是某个Python项目的学习记录,项目地址。不论是初学者还是已经使用过Python一段时间的人都可以过一遍这个项目,都能有所收获,并在过完后不由得感叹于 Python 那丰富的原生“轮子”,利用得当的话,可以避免大量重复“造轮子”的工作,尤其是自己造出来的“轮子”往往没有那么高效。诚然,这个项目相较于 Python 使用手册来说,也只是展示了 Python 语言强大功能的冰山一角,so, never stop learning.

I. 笔记

1. Date 篇

  1. datetime 是 Python 中集中支持日期相关操作的模块。datetime 中常用的类有 date, datetime 和 timedelta. 其中 datetime 继承自 date, 意味着 date 中可用的方法 datetime 也可用。date 和 datetime 用于在不同的精度水平上表示日期,而 timedelta 用于日期差。

    • date/datetime + timedelta = date calculator
    • timedelta.days
  2. 日期的 ISO 格式

    ISO 8601 is an internationally agreed way to represent dates. In Python ISO 8601 date is represented in YYYY-MM-DDTHH:MM:SS.mmmmmm format. For example, May 18, 2022, is represented as 2022-05-18T11:40:22.519222.

    • date/datetime.fromisoformat()
    • date/datetime.isoformat()
  3. 工作日/双休日的判定

    • date/datetime.weekday(): Monday == 0 … Sunday == 6.

2. Dictionary 篇

  1. collections.defaultdict

    • 不要忘记在返回结果时用 dict() 把 defaultdict 转化为正常的 dictionary
    • 可使用匿名函数 lambda 来为 defaultdict 指定特定的默认值
  2. collections.namedtuple

    • 增加代码可读性
    • 可以为元组指定默认值 (缺省默认值按照从右到左的顺序)
  3. functools.reduce

  4. sorted(reverse=False, key=None)

    • reverse=False: 数值从小到大
    • key 关键字: 可以是某个函数或匿名函数,十分好用
    • min()max() 也支持 key 关键字
  5. operator 模块

    • add, sub, getitem etc.
  6. 列表/字典/元组/集合表达式 (list/dict/tuple/set comprehension)

    例如: [item + 1 for item in lst], 可结合 map(), zip(), lambda 等实现更灵活好用的功能

  7. 常用的字典迭代器

    • dict.keys()
    • dict.values()
    • dict.items()
  8. 其他

    • dict.get(): 支持默认值,避免 KeyError,比 dict[key] 要好一些
    • dict.update(): add new items or update existing items
    • dict(zip(list1, list2)) 等价于 {k: v for k, v in zip(list1, list2)}
    • list(dict.items()) 等价于 [(k, v) for k, v in dict.items()]

3. Function 篇

  1. 尽量避免使用可变对象来做默认参数

    Default arguments in Python are evaluated/computed/initialized only once. The evaluation happens when the function is defined, instead of every time the function is called. This can inadvertently create hidden shared state.

    If you absolutely need to use a mutable object as the default value in a function, you can set the default value of the argument to None instead. Then, checking in the function body if it is None, you can set it to the mutable value you want without side effects.

  2. functools.partial

    Partial functions allow us to fix a certain number of arguments of a function and generate a new function.

  3. Double lambda 的使用

    例如:lambda f, g: lambda *args: f(g(*args) 会得到一个以函数为返回值的匿名函数。在本例中,这一返回函数的具体功能是组合两个函数 f 和 g 的功能,并按照先 g 后 f 的顺序进行运算。

4. List 篇

  1. builtins 模块

    • any()all()
    • sorted()
    • filter(function or None, iterable)
      • 尤其注意: If function is None, return the items that are true.
    • map(func, *iterables) --> map object
    • zip(*iterables) --> zip object
      • sorted()zip() 结合可以用于处理一些跟索引相关的问题, i.e., sorted(zip(*, *), key=*, reverse=*)
    • next(iterator[, default])
      • Return the next item from the iterator
  2. list 类

    • list.append()list.extend()
    • list.sort()sorted() 的区别
    • list.index(val)
      • list.index(max(list)) 等价于
        sorted(zip(list, range(len(list))), reverse=True)[0][1]
      • list.index(min(list)) 等价于
        sorted(zip(list, range(len(list))), reverse=False)[0][1]
    • list.count(val)
  3. random 模块

    • 随机元素

      • random.choice()
      • random.choices()
      • random.sample()
    • 乱序

      • random.shuffle()
  4. 翻转列表/字符串

    • list[::-1]
    • str[::-1]
  5. 计数相关

    • list.count(val)
    • collections.Counter
      • Counter.most_common(n)
  6. 独一无二的元素相关

    • set()
    • collections.Counter
  7. 嵌套的列表表达式 (nested list comprehension)

    例如, [[val for i in range(width)] for j in range(height)]

  8. 切片

    • A negative step means that the list is sliced in reverse (from end to start). This also means that start should be greater than stop.
    • 浅拷贝: nums_clone = nums[:]
    • 切片赋值:
      • 步长为一 (step = 1): 可以改变列表长度
      • 步长不为一 (step != 1): 必须保持长度一致

5. Math 篇

  1. str.format() 中的数据类型: b, d, o, x, e, f, c, %, etc.

  2. functools.reduce: 省时省力,十分好用

  3. map(func, *iterables) --> map object 的应用

    • one iterable

      map(lambda x: x + 1, [1, 2, 3])

    • multiple iterables

      map(lambda x, y: x + y, [1, 2, 3], [4, 5, 6])

  4. from itertools import chain, combinations

    • chainchain.from_iterable 的区别
    • 均不具备递归 (recursion) 的能力
  5. builtins 模块

    • sum()
    • len()
    • min(), max()
    • divmod(x, y): Return the tuple (x // y, x % y)
    • int(x, base=10): Return decimal (i.e., base 10) representation of x
  6. math 模块

    • comb(): 组合数
    • math.copysign()
    • math.gcd(): 最大公约数 (greatest common divisor),稍作转化也可用于计算最小公倍数 (least common multiple)
    • math.pi: 圆周率常数
  7. 十进制数到二/八/十六进制

    • bin()
    • oct()
    • hex()
  8. 二/八/十六进制到十进制数: int(x, base=2/8/16)

  9. Python 的位运算 (Bitwise Operators)

    • &
    • |
    • ~
    • ^
    • >>
    • <<

6. String 篇

  1. Python 正则表达式

  2. 常见的命名方式:驼峰 (Camel Case, camelCase),烤肉 (Kebab Case, kebab-case),蛇形 (snake_case) 等

  3. str 类

    • 字符串编码: str.encode()
      • len(s.encode('utf-8')) 可用于计算字符串字节长度
    • 字符串大小写转化:
      • str.lower(), str.casefold()
      • str.upper()
      • str.title()
    • 字符串填充/对齐
      • str.ljust()
      • str.rjust()
      • str.center()
      • str.zfill()
    • 字母数字字符串判定
      • str.isalnum()
      • str.isalpha()
      • str.isnumeric()
    • 去除字符串中的 whitespace 字符, 包括 space (), tab (\t), newline (\n), and carriage return characters (\r)
      • str.strip()
      • str.lstrip()
      • str.rstrip()
    • 字符串分割: str.split()
      • str.splitlines(): str.splitlines() 不完全等同于 str.split(\n)
    • 字符串连接: str.join()
    • 字符串计数: str.count(char)
      • collections.Counter
  4. 字符串格式化

    • f-string
    • str.format()
  5. 字符串/列表翻转

    • str[::-1]
    • list[::-1]

II. 资源


30 Seconds of Code: Python
https://zray111.github.io/2022/12/05/30-seconds-of-code-Python/
作者
ZRay
发布于
2022年12月5日
许可协议