在Python 3.8版本中,新的运算符——海象运算符 :=。这个运算符因形似海象的嘴巴和胡须而得名,它能让你在表达式中进行赋值,使代码变得更优雅、更简洁。
在Python中,:= 被称为赋值表达式,它允许你在表达式的任何位置进行赋值操作,而不必单独写一个赋值语句。这在循环、条件判断、函数调用中尤其有用,可以减少代码行数并提高可读性。
示例代码
# 示例1:在while循环中使用
1 | lines = ["Hello", "World", "Python"]while (line := lines.pop()) != "Python": print(line)print("Found Python!") |
# 示例2:在for循环中初始化计数器
1 | for (i := 0) in range(10): print(i) |
# 示例3:列表推导式中使用
1 | numbers = [1, 2, 3, 4, 5]squares = [(n := n**2) for n in numbers]print(squares) |
# 示例4:在if条件中使用
1 | if (value := 42) > 10: print(f"Value is greater than 10: {value}") |
# 示例5:函数调用前的检查
1 | def process_data(data): print(f"Processing data: {data}")data = [1, 2, 3]if (d := len(data)) > 0: process_data(d) |
# 示例6:与逻辑运算符结合使用
1 | if (file := open('example.txt')) and (content := file.read()): print(content)finally: file.close() |
# 示例7:字典推导式中使用
1 | data = {'a': 1, 'b': 2}keys = ['a', 'b', 'c']mapped_data = {k: data[k] if (k := k) in data else None for k in keys}print(mapped_data) |
# 示例8:列表过滤
1 | words = ['Python', 'is', 'awesome']long_words = [word for word in words if (len(word) := len(word)) > 5]print(long_words) |
# 示例9:生成器表达式中使用
1 | gen = ((i := i+1) for i in range(5))for num in gen: print(num) |
# 示例10:在元组解包中使用
1 | t = (1, 2, 3)(a := t[0], b := t[1], c := t[2])print(f"a={a}, b={b}, c={c}") |