Python 3.5 带给我们的方便的矩阵以及其他改进

探索一些未被充分利用但仍然有用的 Python 特性。

探索一些未被充分利用但仍然有用的 Python 特性。

Python 3.5 带给我们的方便的矩阵以及其他改进

这是 Python 3.x 首发特性系列文章的第六篇。Python 3.5 在 2015 年首次发布,尽管它已经发布了很长时间,但它引入的许多特性都没有被充分利用,而且相当酷。下面是其中的三个。

@ 操作符

@ 操作符在 Python 中是独一无二的,因为在标准库中没有任何对象可以实现它!它是为了在有矩阵的数学包中使用而添加的。

矩阵有两个乘法的概念。元素积是用 * 运算符完成的。但是矩阵组合(也被认为是乘法)需要自己的符号。它是用 @ 完成的。

例如,将一个“八转”矩阵(将轴旋转 45 度)与自身合成,就会产生一个四转矩阵。

“`
import numpy

hrt2 = 2**0.5 / 2
eighthturn = numpy.array([
[hrt2, hrt2],
[-hrt2, hrt2]
])
eighth
turn @ eighth_turn

“`

“`
array([[ 4.26642159e-17, 1.00000000e+00],
[-1.00000000e+00, -4.26642159e-17]])

“`

浮点数是不精确的,这比较难以看出。从结果中减去四转矩阵,将其平方相加,然后取其平方根,这样就比较容易检查。

这是新运算符的一个优点:特别是在复杂的公式中,代码看起来更像基础数学:

“`
almostzero = ((eighthturn @ eighthturn) – numpy.array([[0, 1], [-1, 0]]))**2
round(numpy.sum(almost
zero) ** 0.5, 10)

“`

“`
0.0

“`

参数中的多个关键词字典

Python 3.5 使得调用具有多个关键字-参数字典的函数成为可能。这意味着多个默认值的源可以与更清晰的代码”互操作“。

例如,这里有个可笑的关键字参数的函数:

“`
def showstatus(
*,
the
good=None,
thebad=None,
the
ugly=None,
fistful=None,
dollars=None,
more=None
):
if thegood:
print(“Good”, the
good)
if thebad:
print(“Bad”, the
bad)
if theugly:
print(“Ugly”, the
ugly)
if fistful:
print(“Fist”, fistful)
if dollars:
print(“Dollars”, dollars)
if more:
print(“More”, more)

“`

当你在应用中调用这个函数时,有些参数是硬编码的:

“`
defaults = dict(
thegood=”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 在六年前就已经发布了,但是在这个版本中首次出现的一些特性非常酷,而且没有得到充分利用。如果你还没使用,那么将他们添加到你的工具箱中。


via: https://opensource.com/article/21/5/python-35-features

作者:Moshe Zadka 选题:lujun9972 译者:geekpi 校对:wxy

本文由 LCTT 原创编译,Linux中国 荣誉推出

主题测试文章,只做测试使用。发布者:eason,转转请注明出处:https://aicodev.cn/2021/06/02/python-3-5-%e5%b8%a6%e7%bb%99%e6%88%91%e4%bb%ac%e7%9a%84%e6%96%b9%e4%be%bf%e7%9a%84%e7%9f%a9%e9%98%b5%e4%bb%a5%e5%8f%8a%e5%85%b6%e4%bb%96%e6%94%b9%e8%bf%9b/

(0)
eason的头像eason
上一篇 2021年6月1日
下一篇 2021年6月2日

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信