Invalid syntax python starred expressions

自古美人都是妖i 提交于 2019-11-27 17:46:22

问题


I am trying to unpack set of phone numbers from a sequence, python shell in turn throws an invalid syntax error. I am using python 2.7.1. Here is the snippet

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

Please explain. Is there any other way of doing the same?


回答1:


You are using Python 3 specific syntax in Python 2.

The * syntax for extended iterable unpacking in assignments is not available in Python 2.

See Python 3.0, new syntax and PEP 3132.

Use a function with * splat argument unpacking to simulate the same behaviour in Python 2:

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

name, email, phone_numbers = unpack_three(*user_record)

or use list slicing.




回答2:


This new syntax was introduced in Python 3. So, it'll raise error in Python 2.

Related PEP: PEP 3132 -- Extended Iterable Unpacking

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
>>> 



回答3:


That functionality is only available in Python 3, an alternative is:

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

Or something like:

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

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

but that is pretty hacky IMO



来源:https://stackoverflow.com/questions/16563623/invalid-syntax-python-starred-expressions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!