Python是第三大常用的编程语言。它引入了许多新功能,简化和增强了开发过程。然而,许多开发人员仍未意识到Python 3必须提供的全部潜力。
本文将在Python中发现十个鲜为人知的和未充分利用的功能(v3.5至v3.11)。这些隐藏的宝石可以提高您的编码效率和生产力。因此,事不宜迟,让我们深入研究这些引人入胜的Python 3个特征。
1.海象操作员
是Python 3.11中引入的一种新的语法,将值分配给变量作为较大表达式的一部分。
旧方法
a = "This is a sample string text"
if len(a) > 10:
print("Length of string a = ", len(a))
新方法
a = "This is a sample string text"
if (len_a := len(a)) > 10: # Note the walrus operator will compute value of len(a) and assign it to variable len_a
print("Length of string a = ", len_a)
2.结构模式匹配
您可能还记得读过python没有支持开关语句,因为如果else可以达到相同的结果。您正在待命。 Python3.10引入了类似的东西。
旧方法
def http_error(status):
if status == 400:
return "Bad request"
elif status == 404:
return "Not found"
elif status == 418:
return "I'm a teapot"
else:
return "Something's wrong with the internet"
新方法
def http_error(status):
match status:
case 400:
return "Bad request"
case 404:
return "Not found"
case 418:
return "I'm a teapot"
case _: # This is a wildcard operator
return "Something's wrong with the internet"
3.合并词典
Python3.9引入了一种合并或更新词典的新方法。它补充了现有的dict.update和{** d1,** d2}合并字典的方法。
旧方法
x = {"key1": "value1 from x", "key2": "value2 from x"}
y = {"key2": "value2 from y", "key3": "value3 from y"}
print({ **x,** y})
print({ **y,** x}) # Note here keys of y would be given preference over keys of x
新方法
x = {"key1": "value1 from x", "key2": "value2 from x"}
y = {"key2": "value2 from y", "key3": "value3 from y"}
# Note the usage of OR (|) operator
print(x | y)
prin(y | x) # Note here keys of y would be given preference over keys of x
4.删除前缀或后缀
Python3.9引入了专门的方法,以摆脱字符串中的前缀或后缀。
旧方法
x = "prefixstring"
y = "stringsuffix"
print(x.split("prefix")[-1])
print(y.split("suffix")[0])
新方法
x = "prefixstring"
y = "stringsuffix"
print(x.removeprefix("prefix"))
print(y.removesuffix("suffix"))
5.只有位置参数
Python提供了为函数定义位置和关键字参数。但是您可以互换传递它们。 Python3.8引入了一种方法来强制执行您不能将位置参数作为关键字参数。
旧方法
def fun(pos_arg1, pos_arg2, key_arg_1 = None):
print("positional arguments: ", pos_arg1, pos_arg2)
print("Keyword arguments: ", key_arg_1)
# It will work
fun(1, 2, 3) # Passing keyword argument as positional argument
# It will also work
fun(pos_arg1=1, pos_arg2=2, key_arg_1=3) # Passing positional argument as keyword argument
新方法
def fun(pos_arg1, pos_arg2, /, key_arg_1 = None):
print("positional arguments: ", pos_arg1, pos_arg2)
print("Keyword arguments: ", key_arg_1)
# It will work
fun(1, 2, 3) # Passing keyword argument as positional argument
# It won't work
fun(1, pos_arg2=2, key_arg_1=3) # Passing one positional argument as keyword argument
fun(pos_arg1=1, pos_arg2=2, key_arg_1=3) # Passing both positional arguments as keyword argument
6.纳秒精度的时间
您是否曾经需要纳秒精度来比较代码性能? Python3.7在时间库中引入了新方法。
旧方法
import time
start = time.time()
end = time.time()
print(end - start)
# Provides sub-second precision, though that precision varies by platform
# >> 2.7179718017578125e-05 Notice the precision is in e-05
新方法
import time
start = time.time_ns()
end = time.time_ns()
print(end - start)
# Provides nanosecond precision
# >> 47000 Notice the figure is in nanoseconds
7. F串
Python3.6引入了F串,以提供一种简单的格式化字符串的方法。
旧方法
a = 1
print("Value of a = {}".format(a))
新方法
a = 1
print(f"Value of a = {a}")
8.在数字文字中强调
Python 3.6引入了允许在数字文字中添加下划线以获得更好的可读性。
旧方法
a = 1000000000000000 # try counting the number of 0's
print(type(a))
# >> <class 'int'>
新方法
a = 1_000_000_000_000_000
print(type(a))
# >> <class 'int'>
9.矩阵乘法运算符
Python3.5引入了矩阵乘法的专用 @ infix运算符。
旧方法
import numpy
x = numpy.ones(3)
m = numpy.eye(3)
print(x.dot(m))
新方法
import numpy # NumPy 1.10 has support for the new operator:
x = numpy.ones(3)
m = numpy.eye(3)
print(x @ m) # @ is the new matrix matrix-multiplication operator
10.近似平等
Python3.5引入了专用方法,以判断两个值大约相等还是彼此接近。
旧方法
a = 5.0
b = 4.99998
print(abs(a - b) <= 1e-5)
新方法
import math
a = 5.0
b = 4.99998
print(math.isclose(a, b, rel_tol=1e-5))