语法python已加星标表达式无效

use*_*591 12 python iterable-unpacking

我试图从一个序列解压缩一组电话号码,python shell反过来抛出一个无效的语法错误.我正在使用python 2.7.1.这是片段

 >>> record = ('Dave', 'dave@example.com', '773-555-1212', '847-555-1212')
 >>> name, email, *phone-numbers = record
 SyntaxError: invalid syntax
 >>>
Run Code Online (Sandbox Code Playgroud)

请解释.有没有其他方法做同样的事情?

Mar*_*ers 18

您在Python 2中使用Python 3特定语法.

*Python 2中没有在赋值中扩展可迭代解包的语法.

请参阅Python 3.0,新语法PEP 3132.

使用带有*splat参数解包的函数来模拟Python 2中的相同行为:

def unpack_three(arg1, arg2, *rest):
    return arg1, arg2, rest

name, email, phone_numbers = unpack_three(*user_record)
Run Code Online (Sandbox Code Playgroud)

或使用列表切片.


Ash*_*ary 14

Python 3引入了这种新语法.因此,它会在Python 2中引发错误.

相关PEP:PEP 3132 - 扩展的可迭代解包

name, email, *phone_numbers = user_record
Run Code Online (Sandbox Code Playgroud)

Python 3:

>>> a, b, *c = range(10)
>>> a
0
>>> b
1
>>> c
[2, 3, 4, 5, 6, 7, 8, 9]
Run Code Online (Sandbox Code Playgroud)

Python 2:

>>> a, b, *c = range(10)
  File "<stdin>", line 1
    a,b,*c = range(10)
        ^
SyntaxError: invalid syntax
>>> 
Run Code Online (Sandbox Code Playgroud)


jam*_*lak 8

该功能仅在Python 3中可用,另一种方法是:

name, email, phone_numbers = record[0], record[1], record[2:]
Run Code Online (Sandbox Code Playgroud)

或类似的东西:

>>> def f(name, email, *phone_numbers):
        return name, email, phone_numbers

>>> f(*record)
('Dave', 'dave@example.com', ('773-555-1212', '847-555-1212'))
Run Code Online (Sandbox Code Playgroud)

但这是非常hacky IMO