便捷的矩阵以及 Python 3.5 为我们带来的其他改进

探索一些未被充分利用但仍然有用的 Python 功能。
44 位读者喜欢这个。

这是关于 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 是在六年前发布的,但此版本中首次出现的一些功能很酷且未被充分利用。如果您还没有这样做,请将它们添加到您的工具包中。

接下来阅读什么
标签
Moshe sitting down, head slightly to the side. His t-shirt has Guardians of the Galaxy silhoutes against a background of sound visualization bars.
自 1998 年以来,Moshe 一直参与 Linux 社区,帮助举办 Linux “安装聚会”。他从 1999 年开始编写 Python 程序,并为核心 Python 解释器做出了贡献。Moshe 自这些术语出现之前就一直是 DevOps/SRE,他非常关心软件可靠性、构建可重复性以及其他此类事情。

评论已关闭。

Creative Commons License本作品根据 Creative Commons Attribution-Share Alike 4.0 International License 许可。
© . All rights reserved.