第一个是 this
n=int(input())
a=[]
for i in range(n):
a.append(int(input()))
第二个是此:
n=int(input())
a=[0]*n
for i in range(n):
a[i]=int(input())
我一直在使用第一个,但我刚想到了第二个。我不知道append
的工作方式,但我认为第二个可能比第一个更有效。
我可以得到这个问题的答案吗?
答案 0 :(得分:1)
我相信不应有确切的答案,因为这将取决于哪个版本的Python,哪个平台等。
但是总的来说,这是您想要做的快速测试:
创建一个文件,例如testcode.py
,然后执行以下操作:
def first():
n=100000
a=[]
for i in range(n):
a.append(int("42"))
def second():
n=100000
a=[0]*n
for i in range(n):
a[i]=int("42")
然后运行timeit:
$ python -m timeit -s 'from testcode import first, second' -- 'first()'
10 loops, best of 5: 27.1 msec per loop
$ python -m timeit -s 'from testcode import first, second' -- 'second()'
10 loops, best of 5: 23.6 msec per loop