Python 在 3.8 版本之后引入了海象算子,它主要有三种用法
- 使用在
if
语句中
if (n := len(a)) > 10:
print(f"List is too long ({n} elements, expected <= 10)")
- 用在
while
语句中
while (block := f.read(256)) != '':
process(block)
- 用在列表推导式中
[clean_name.title() for name in names
if (clean_name := normalize('NFC', name)) in allowed_names]