这是关于 Python 3.x 版本中首次出现的功能系列文章中的第六篇。Python 3.5 于 2015 年首次发布,即使它已经发布很长时间了,但它引入的许多功能都未被充分利用,而且非常酷。以下是其中三个。
@ 运算符
@
运算符在 Python 中是独一无二的,因为标准库中没有对象实现它!添加它是为了在具有矩阵的数学包中使用。
矩阵有两个乘法概念;逐点乘法使用 *
运算符完成。但是矩阵合成(也认为是乘法)需要它自己的符号。它使用 @
完成。
例如,将“八分之一转”矩阵(将轴旋转 45 度)与其自身合成会得到四分之一转矩阵
import numpy
hrt2 = 2**0.5 / 2
eighth_turn = numpy.array([
[hrt2, hrt2],
[-hrt2, hrt2]
])
eighth_turn @ eighth_turn
array([[ 4.26642159e-17, 1.00000000e+00],
[-1.00000000e+00, -4.26642159e-17]])
浮点数是不精确的,这更难看出来。通过从结果中减去四分之一转矩阵,对平方求和并取平方根来检查更容易。
这是新运算符的一个优势:尤其是在复杂的公式中,代码看起来更像底层的数学
almost_zero = ((eighth_turn @ eighth_turn) - numpy.array([[0, 1], [-1, 0]]))**2
round(numpy.sum(almost_zero) ** 0.5, 10)
0.0
参数中的多个关键字字典
Python 3.5 使使用多个关键字参数字典调用函数成为可能。这意味着多个默认来源可以“协作”并使代码更清晰。
例如,这是一个带有大量关键字参数的函数
def show_status(
*,
the_good=None,
the_bad=None,
the_ugly=None,
fistful=None,
dollars=None,
more=None
):
if the_good:
print("Good", the_good)
if the_bad:
print("Bad", the_bad)
if the_ugly:
print("Ugly", the_ugly)
if fistful:
print("Fist", fistful)
if dollars:
print("Dollars", dollars)
if more:
print("More", more)
当您在应用程序中调用此函数时,某些参数是硬编码的
defaults = dict(
the_good="You dig",
the_bad="I have to have respect",
the_ugly="Shoot, don't talk",
)
更多参数从配置文件中读取
import json
others = json.loads("""
{
"fistful": "Get three coffins ready",
"dollars": "Remember me?",
"more": "It's a small world"
}
""")
您可以从两个来源一起调用该函数,而无需构造中间字典
show_status(**defaults, **others)
Good You dig
Bad I have to have respect
Ugly Shoot, don't talk
Fist Get three coffins ready
Dollars Remember me?
More It's a small world
os.scandir
os.scandir
函数是迭代目录内容的新方法。它返回一个生成器,该生成器产生关于每个对象的丰富数据。例如,以下是一种打印目录列表的方法,并在目录末尾带有尾随 /
for entry in os.scandir(".git"):
print(entry.name + ("/" if entry.is_dir() else ""))
refs/
HEAD
logs/
index
branches/
config
objects/
description
COMMIT_EDITMSG
info/
hooks/
欢迎来到 2015 年
Python 3.5 是在六年前发布的,但此版本中首次出现的一些功能很酷且未被充分利用。如果您还没有这样做,请将它们添加到您的工具包中。
评论已关闭。