gpt4 book ai didi

python - 函数调用之外的星号

转载 作者:行者123 更新时间:2023-11-28 19:06:02 25 4
gpt4 key购买 nike

我正在尝试使用 python,我有一个关于星号的问题。我知道它们用于函数调用中的参数,但我已经看到在函数卡之外使用它们的代码片段(例如,在 5 年级的元组中,将它们解压缩到变量中,例如:

first, *middle, last = 成绩

每当我尝试在函数调用的参数之外的上下文中使用星号时,我都会在解释器中得到无效语法。我在这里遗漏了什么吗?

最佳答案

Python 3 添加了扩展元组解包,支持one 通配符,参见PEP 3132 :

*start, tail = ...
head, *middle, tail = ...

参见 assignment statements引用文档:

If the target list contains one target prefixed with an asterisk, called a “starred” target: The object must be a sequence with at least as many items as there are targets in the target list, minus one. The first items of the sequence are assigned, from left to right, to the targets before the starred target. The final items of the sequence are assigned to the targets after the starred target. A list of the remaining items in the sequence is then assigned to the starred target (the list can be empty).

在赋值的左侧(目标列表)使用星号是 Python 2 中的语法错误。

关于python - 函数调用之外的星号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46611650/

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