Think Python Exercise 10.9

编写一个函数,读取文件 words.txt ,建立一个列表,其中每个单词为一个元素。

编写两个版本,一个使用 append 方法,另一个使用 t = t + [x] 。那个版本运行得慢?为什么?

解答:

在 jupyter 中的一个代码单元(cell)中,代码第一行写上%%time或%%timeit,即可计算代码的运行时间。

版本1:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
%%time

def read_word1(file_in):
    word_list = []
    for line in file_in:
        word = line.strip()
        word_list.append(word)
    return word_list

fin = open('words.txt')

a = read_word1(fin)

运行结果:

CPU times: user 85.3 ms, sys: 0 ns, total: 85.3 ms Wall time: 88.4 ms

版本2:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
%%time

def read_word2(file_in):
    word_list = []
    for line in file_in:
        word = line.strip()
        word_list = word_list + [word] #相当于word_list这个列表和一个只有一个元素的列表合并
    return word_list

fin = open('words.txt')

a = read_word2(fin)

运行结果:

CPU times: user 1min 1s, sys: 13.5 ms, total: 1min 1s Wall time: 1min 1s

结果很显然,即便不准确测量也能感知到,第二个版本的代码相比第一个慢了很多。

第一版的代码,每次循环,仅仅是操作一个元素,把它追加到列表末端;而第二版的代码,每次循环都要进行一次两个列表的拼接。