2024-04-20 09:08:34 发布
网友
我正试图从序列中解压一组电话号码,python shell反过来抛出一个无效语法错误。我正在使用Python2.7.1。这是片段
>>> record = ('Dave', 'dave@example.com', '773-555-1212', '847-555-1212') >>> name, email, *phone-numbers = record SyntaxError: invalid syntax >>>
请解释一下。还有别的办法吗?
这个新语法是introduced in Python 3。所以,它会在Python 2中引发错误。
相关政治公众人物:PEP 3132 -- Extended Iterable Unpacking
name, email, *phone_numbers = user_record
Python3:
>>> a, b, *c = range(10) >>> a 0 >>> b 1 >>> c [2, 3, 4, 5, 6, 7, 8, 9]
Python2:
>>> a, b, *c = range(10) File "<stdin>", line 1 a,b,*c = range(10) ^ SyntaxError: invalid syntax >>>
您在Python 2中使用的是Python 3特定的语法。
Python 2中没有用于在赋值中扩展iterable解包的*语法。
*
见Python 3.0, new syntax和PEP 3132。
使用带*splat参数解包的函数来模拟Python 2中的相同行为:
def unpack_three(arg1, arg2, *rest): return arg1, arg2, rest name, email, phone_numbers = unpack_three(*user_record)
或者使用列表切片。
该功能仅在Python3中可用,另一种方法是:
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'))
但我觉得这很老套
这个新语法是introduced in Python 3。所以,它会在Python 2中引发错误。
相关政治公众人物:PEP 3132 -- Extended Iterable Unpacking
Python3:
Python2:
您在Python 2中使用的是Python 3特定的语法。
Python 2中没有用于在赋值中扩展iterable解包的
*
语法。见Python 3.0, new syntax和PEP 3132。
使用带
*
splat参数解包的函数来模拟Python 2中的相同行为:或者使用列表切片。
该功能仅在Python3中可用,另一种方法是:
或者类似于:
但我觉得这很老套
相关问题 更多 >
编程相关推荐