2020年9月24日 / 30次阅读 / Last Modified 2020年9月24日
语法
从python3.8开始,支持海象操作符(walrus operator :=),对应PEP572。
海象操作符的特点是将赋值和判断放在一起,简化了代码,提高了效率。其实,C语言早就是这样的使用,比如在if直接用一个=赋值,然后对赋值后的变量进行判断。Python从3.8开始支持,反正是有了吧。据说Go语言一开始就有。
>>> a = [1,2,3,4,5,6,7]
>>> if len(a) > 5:
... print('length of a: %d' % len(a)) # call len twice
...
length of a: 7
>>>
>>> if n := len(a) > 5: # wrong, > will be executed first
... print('length of a: %d' % n)
...
length of a: 1
>>>
>>> if (n := len(a)) > 5: # call len only once, assign n and compare
... print('length of a: %d' % n)
...
length of a: 7
看上面的示例代码,第一段是传统写法,调用了2次len函数;第二段是错误的,大于符号的优先级高于海象符号(为什么是这样,请参考:python的连续赋值);第三段才是主题,在if中直接给变量n赋值,然后对 n > 5进行判断。
>>> s
'abcde 12345 pynote.net'
>>> ore = re.search(r'\d+', s)
>>> if ore:
... print(ore.group())
...
12345
>>>
>>> if ore := re.search(r'\d+', s):
... print(ore.group())
...
12345
>>> if ore := re.search(r'tiantian', s):
... print(ore.group())
... else:
... print('not found')
...
not found
>>> ore
>>> ore is None
True
以上是另一段示例,注意最后一段在if中assign的ore对象是None。
>>> ss
['abcde', 'bcdef', 'a123', '000', 'b123', 'a444']
>>>
>>> def string_sum(ss):
... return sum([ord(x) for x in ss])
>>>
>>> [x for i in ss if (x:=string_sum(i)) > 100]
[495, 500, 247, 144, 248, 253]
海象操作符在list comprehension中的应用。
while (line := file.readline()):
pass # your code here
-- EOF --
本文链接:https://www.pynote.net/archives/2497
《海象操作符(:=)》有1条留言
前一篇:hashlib模块的使用
后一篇:用ThreadPoolExecutor创建线程池
Ctrl+D 收藏本页
©Copyright 麦新杰 Since 2019 Python笔记
Python早该有这个操作符了!C语言一开始就有,有些时候太TM好用了,代码非常清爽,适合强迫症程序员。 [ ]