使用带打印的*(splat)运算符

Ran*_*ook 6 python python-2.7

我经常使用Python的print语句来显示数据.是的,我知道'%s %d' % ('abc', 123)方法,'{} {}'.format('abc', 123)方法和' '.join(('abc', str(123)))方法.我也知道splat operator(*)可以用来将iterable扩展为函数参数.但是,我似乎无法用print声明做到这一点.使用列表:

>>> l = [1, 2, 3]
>>> l
[1, 2, 3]
>>> print l
[1, 2, 3]
>>> '{} {} {}'.format(*l)
'1 2 3'
>>> print *l
  File "<stdin>", line 1
    print *l
          ^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

使用元组:

>>> t = (4, 5, 6)
>>> t
(4, 5, 6)
>>> print t
(4, 5, 6)
>>> '%d %d %d' % t
'4 5 6'
>>> '{} {} {}'.format(*t)
'4 5 6'
>>> print *t
  File "<stdin>", line 1
    print *t
          ^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

我错过了什么吗?这根本不可能吗?接下来会发生什么print?该文件说,一个逗号分隔的表达式列表按照print关键字,但我猜这是不一样的列表数据类型.我在SO和网络上做了很多挖掘,并没有找到明确的解释.

我使用的是Python 2.7.6.

iCo*_*dez 12

print是Python 2.x中的一个语句,不支持*语法.您可以从文档中print列出的语法中看到这一点:

print_stmt ::=  "print" ([expression ("," expression)* [","]]
                | ">>" expression [("," expression)+ [","]])

请注意*print关键字后面没有使用选项.


然而,*语法支持内部函数调用,它只是恰巧print是在Python 3.X的功能.这意味着您可以从__future__以下位置导入:

from __future__ import print_function
Run Code Online (Sandbox Code Playgroud)

然后使用:

print(*l)
Run Code Online (Sandbox Code Playgroud)

演示:

>>> # Python 2.x interpreter
>>> from __future__ import print_function
>>> l = [1, 2, 3]
>>> print(*l)
1 2 3
>>>
Run Code Online (Sandbox Code Playgroud)

  • `*`语法实际上是[函数调用语法]的一部分(https://docs.python.org/2/reference/expressions.html#calls); 它不是一个独立的运营商.`print`不支持它只是因为语言设计师没有决定这样做.最近有一个提议将`*`语法扩展到Python的更多领域,但它还没有实现. (2认同)