简体   繁体   English

在Python中解压* args的顺序

[英]order of unpacking *args in Python

I wonder why variable last is 5 when i do 我不知道为什么当我做时变量last5

first, *rest, last = 1,2,3,4,5

I thought assignment goes from left to right, thus *rest will be [2,3,4,5] , but it actualy is [2,3,4] And I thought that last will be empty, or this code will cause error, but suprisingly it works, but I dont understand why 我以为赋值从左到右,因此*rest将是[2,3,4,5] ,但实际上是[2,3,4]并且我以为last将为空,否则此代码将导致错误,但令人惊讶的是它有效,但是我不明白为什么

这是仅在Python 3中有效的语法,称为“扩展解压缩”,并且在PEP 3132中定义-https: //www.python.org/dev/peps/pep-3132/

Just because it's unpacking feature. 只是因为它具有拆包功能。

first and last are just variables, when *rest are arguments, so they get everything between first and last value in tuple (1,2,3,4,5). *rest是参数时, firstlast只是变量,因此它们获得元组(1,2,3,4,5)中firstlast值之间的所有值。

If you want to have you wrote: 如果您想写:

[2,3,4,5]

then just use: 然后只需使用:

first, *args = 1,2,3,4,5
# first --> 1
# args --> [2,3,4,5] 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 python 元组:使用 *args 解包到列表中 - python tuples: unpacking into a list using *args Python模拟call_args_list拆包元组以声明参数 - Python mock call_args_list unpacking tuples for assertion on arguments Python - 方法参数中的值解包顺序 - Python - value unpacking order in method parameters function *args 的字典解包列表 - Unpacking List of Dicts for function *args python参数解包在哪里属于操作顺序? - Where does python argument unpacking fall into the order of operations? python 使用 *args 和 **kwargs 以及其他仅位置和关键字参数解包 arg 列表 - python unpacking arg list with *args and **kwargs along with other positional and keyword only params Python可以打*(拆包)操作符吗? 或者任何其他可变参数 function 使得所有可变参数类型都在结果类型中? - Can the * (unpacking) operator be typed in Python? Or any other variadic args function such that all variadic types are in the result type? 是否可以保证Python3中的* args保留顺序? - Is *args in Python3 guaranteed to preserve order? 迭代拆包评估单 - Iterable Unpacking Evaluation Order 为什么 *args 参数解包会给出一个元组? - Why does *args argument unpacking give a tuple?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM