2017-07-20 30 views
0

在书流利Python中,我发现在一些listcomp_speed.py代码,它运行得很好python3.5,但它在python2.7上升语法错误。代码是:在python2.7上升语法错误打印的星号

def clock(label, cmd): 
    res = timeit.repeat(cmd, setup=SETUP, number=TIMES) 
    print(label, *('{:.3f}'.format(x) for x in res)) 

和错误是:

def clock(label, cmd): 
...  res = time.repeat(cmd, setup=SETUP, number=TIMES) 
...  print(label, *('{:3.f}.formart(x) for x in res')) 
File "<stdin>", line 3 
print(label, *('{:3.f}.formart(x) for x in res')) 
      ^
SyntaxError: invalid syntax 

而且它没有任何意义,我,作为打印星号拆包,并拆包是在打印的支持, print(*("1","2")) 将运行良好。

和python3.5运行良好的相同的代码。

书没有说明蟒蛇的环境。

+0

我已经读了这本书,它肯定* *说,它仅用于Python 3中。下面是从[流利的Python页面上O'Reilly的网站]的摘录(http://shop.oreilly.com/product/0636920032519.do):*有了这本书,那些Python程序员将深入学习如何成为精通** Python 3 **。*。 – SethMMorton

+0

@SethMMorton谢谢,在阅读序言时,我将这些状态留给了我。 – wllbll

回答

2

print的Python 2和Python 3之间改变在Python 2,它是不需要括号中的特别声明。在Python 3中,它是一个需要括号的函数,但也可以做更多的事情 - 包括参数,就像你在这里展示的那样。

您可以使用Python 3风格print在Python 2通过在你的文件的顶部写

from __future__ import print_function