Walrus 运算符允许您在表达式中使用属性时为属性分配值。它之所以这样命名,是因为它看起来像海象的眼睛和獠牙 :=。
List Comprehension:half 在列表推导式中被分配!
numbers = [10, 20, 30, 5, 3, 25]large_numbers = [(half, n) for n in numbers if (half := n / 2) > 10]print(large_numbers) # Output: [(15.0, 30), (12.5, 25)]if/else 中: 避免冗余计算(在本例中为 len)。保存额外的行并保持代码干净。
my_list = [1, 'hetero', 'list', 'of length', 5.0]if (n:=len(my_list)) < 10: print(f'this works') #prints this works print(f'I can still print the value of n = {n}')#I can still print the value of n = 5正如你所看到的,它在条件和理解中使用非常有用。您还可以在循环中读取输入,使其更加简洁和可读。虽然您可能希望使用它来减少代码行并使表达式更简洁,但尽量不要过度使用。尤其是在它降低可读性并且常规作业更好的地方。PEP 提案链接→这里
