在 python 3 中输入和打印

input and print in python 3

我们知道 print 语句在 Python 3 中已被弃用,但我们也知道 print() 函数在两者中都存在。其中哪一个更快,弃用在功能方面有何帮助?

input() 功能相同的问题,弃用 raw_input 如何帮助确定 Python 2 和 Python 中 input() 的速度3?

编辑:比较分别基于 iPython 和 iPython3。

这是iPython。

In [1]: %%time
   ...: print("Hello World!")
   ...: 
Hello World!
CPU times: user 0 ns, sys: 0 ns, total: 0 ns
Wall time: 16.2 µs

这是iPython3.

In [1]: %%time
   ...: print("Hello World!")
   ...: 
Hello World!
CPU times: user 0 ns, sys: 0 ns, total: 0 ns
Wall time: 61 µs

Python3好像比较慢!

使print()成为一个功能,更多的是为了提供方便。

  1. 由于 print() 是一个函数,可以通过 def print(...) 或从其他地方导入新函数来替换该函数。

  2. 你可以这样做:

    [print(i) for i in range(10)] # seems a bit impractical, though
    

    f = lambda x: print(x)
    

    您不能使用 print 语句来做到这一点。

  3. print() 函数如下所示:

    def print(*args, sep=' ', end='\n', file=None)
        ...
    
    • args:位置参数,其值将被打印出来。
    • sep:分隔符,将在参数之间打印。
    • end:结束文本,在所有参数输出后打印。
    • file: 输出将发送到的文件对象。

    所以你可以做到

    print(*['a', 'b', 'c', 'd'], sep=", ", end="\nAll values printed")
    # outputs ->
    a, b, c, d
    All values printed
    

    但是你不能用 print 语句做同样的事情。是的,您可以编写一些代码来完成该函数正在做的事情,但正如我所说,print() 函数比它的语句对应物更方便一些。

Python 3 使print成为函数,而不是语句;调用函数总是会增加一些开销。使用 dis 查看两个版本中生成的字节码支持这一点:

脚本:

def print_item(item):
    print(item)

if __name__ == '__main__':
    import dis
    dis.dis(print_item)

2.7.10:

  2           0 LOAD_FAST                0 (item)
              3 PRINT_ITEM          
              4 PRINT_NEWLINE       
              5 LOAD_CONST               0 (None)
              8 RETURN_VALUE        

3.4.3:

  2           0 LOAD_GLOBAL              0 (print)
              3 LOAD_FAST                0 (item)
              6 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
              9 POP_TOP
             10 LOAD_CONST               0 (None)
             13 RETURN_VALUE

然而,在两个版本中超过 1,000 次迭代,使用 timeit,我实际上看到 2.x 中的性能稍慢(2.46 秒对 2.30 秒)。实际上,这是无关紧要的,因为当性能至关重要时 你根本 print 根本

请注意,您可以使用 from __future__ import print_function 在 2.x 中获得 3.x 风格的打印。有关 print 为何成为函数的更多信息,请参阅 PEP-3105


您还提到 input - 2.x 和 3.x 中的实现之间的任何性能差异 完全无关 ,因为等待的时间对于一些笨手笨脚的人来说,键入他们的字符并按 Enter 将比将其作为细绳。也就是说,您可以再次使用 dis 来证明 2.x 中的 raw_input 和 3.x 中的 input 生成相同的字节码。

在Python2、

%timeit print 'foo' 

仅比

快一点点(8.97 对 9.06 us)
from __future__ import print_statement
%timeit print('foo')

在 Python 3 中,那个时间上升到 11 us,这使得 Python 3 比 Python 2 慢不到 20%。这似乎与结果一致当 运行 整个 PyStone 基准测试套件时,人们发现了 here

TLDR:Python 3 仅比 Python 2 慢 - 与打印语句成为函数无关

我看到很多关于 print 的回答。

关于 input() / raw_input() 函数在 python 2.x 和 python 3.x .

在 python 2.x 中,input() 与 raw_input()

略有不同
  1. input() - python 2.x 中的这个函数实际计算输入,然后 returns 它。一个例子 -

    >>> input('Hello : ')
    Hello : 2<3
    True
    
  2. raw_input() - 而 raw_input() 不评估输入,而是将输入作为字符串提供。一个例子-

    >>> raw_input('Hello : ')
    Hello : 2<3
    '2<3'
    

在 python 3.x 中, raw_input() 函数被重命名为 input() ,我猜他们觉得没有必要 input()在评估后提供结果的函数(我也从未见过它的用途,想知道是否有人真的使用过它)