Python语法错误:星号表达式无效

12

我正在尝试从一个序列中解包一组电话号码,但是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
 >>>

请解释一下。有其他做法吗?

3个回答

19

您正在Python 2中使用Python 3特定的语法。

在Python 2中,分配中扩展可迭代解包的*语法不可用。

请参见Python 3.0, new syntaxPEP 3132

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

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

name, email, phone_numbers = unpack_three(*user_record)

或使用列表切片。


14

这种新语法是在Python 3中引入的(introduced in Python 3)。因此,在Python 2中会引发错误。

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

name, email, *phone_numbers = user_record

Python 3:

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

Python 2:

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

8

该功能仅适用于Python 3,另一种替代方法是:

name, email, phone_numbers = record[0], record[1], record[2:]

或者类似于以下内容:
>>> def f(name, email, *phone_numbers):
        return name, email, phone_numbers

>>> f(*record)
('Dave', 'dave@example.com', ('773-555-1212', '847-555-1212'))

但我认为那相当不专业。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接