gpt4 book ai didi

python - Python 的 splat 运算符是……在某一时刻吗?

转载 作者:太空宇宙 更新时间:2023-11-04 09:31:09 25 4
gpt4 key购买 nike

今天,我看到了 pyData 2017 的演讲,演讲者使用了 python 的 splat 运算符 *。想象一下,在他使用该方法之前,当我将其视为指针时,我感到很惊讶。我认为 Python 的 splat 运算符类似于省略号 ... 不是吗?谷歌搜索对我来说一无所获。他们是在某个时候更改了它还是总是 *?如果他们确实改变了它,为什么?如果他们更改它,是否存在实现差异和/或速度差异?

编辑:为愤怒的评论者“解压参数列表”。

最佳答案

不,Python 的解包运算符(有时称为“splat”或“spread”)从未使用过... 省略号。 Python 有 an .../Ellipsis literal value ,但它仅用作单例常量,用于在 NumPy 等库中表达多维范围。它没有内在行为,并且在您将使用 * 解包运算符的位置在语法上无效。

我们可以看到 Python 2.0(2000 年发布)的更改日志 describes the new functionality of being able to use the * unpacking operator to call a function ,但使用 * 星号字符定义可变参数函数(有时称为使用“剩余参数”)比这更早。

A new syntax makes it more convenient to call a given function with a tuple of arguments and/or a dictionary of keyword arguments. In Python 1.5 and earlier, you’d use the apply() built-in function: apply(f, args, kw) calls the function f() with the argument tuple args and the keyword arguments in the dictionary kw. apply() is the same in 2.0, but thanks to a patch from Greg Ewing, f(*args, **kw)is a shorter and clearer way to achieve the same effect. This syntax is symmetrical with the syntax for defining functions.

Python 1.0.1(1994 年发布)的源代码仍然可用from the Python website ,我们可以查看他们的一些示例,以确认即使在那时也存在使用 * 星号字符来定义可变函数。来自 Demo/sockets/gopher.py:

# Browser main command, has default arguments
def browser(*args):
selector = DEF_SELECTOR
host = DEF_HOST
port = DEF_PORT
n = len(args)
if n > 0 and args[0]:
selector = args[0]

关于python - Python 的 splat 运算符是……在某一时刻吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55698221/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com