AI中国网 https: //www.cnaiplus.com
(原标题:详解Python 3.8的海象算子:大幅提高程序执行效率)
前几个月发布的 Python 3.8包含了一项重要的新功能,即海象算子。如果合理运用,该算子能有效地提升 Python 程序的执行效率。本文将对海象算子的作用和效果进行介绍,并会通过示例演示其使用方法和不适用的场景。本文作者为软件工程师 Animesh Gaitonde。
countries = [“India”, “USA”, “France”, “Germany”]if len(countries) < 5:
print ("Length of countries is " + len(countries))
country_size = len(countries)if country_size < 5:
print ("Length of countries is " + country_size)
if country_size := len(countries) < 5 :
print ("Length of countries is " + country_size)
powers = [get_count(), get_count()**2, get_count()**3]
def get_count():
"Fetches count of records from a database"
powers =[result:= get_count(), result**2, result**3]
def get_count():
"Fetches count of records from a database"
employees = []
for id in employee_ids:
employee = fetch_employee(id)
if employee:
employees.append(employee)
employees = [result for id in employee_ids if (result:= fetch_employee(id))]
chunk = file.read(256)
while chunk:
process(chunk)
chunk = file.read(256)
while chunk := file.read(256) :
process(chunk)
obj = re.match(info).group(1) if re.match(info) else None
obj = match.group(1) if match:= re.match(info) else None
a = 5 # 有效
a := 5 # 无效
empty_list = [] # 有效
empty_list := [] # 无效
a += 5 # 有效
a :+=5 # 无效
(lambda: a:= 5) # 无效
lambda: (a := 5) # 有效但无用
(var := lambda: 5) # 有效
AI中国网 https: //www.cnaiplus.com
本文网址: