Skip to main content
 首页 » 编程设计

python之python 的尾部。最佳性能实现

2025年05月04日17Free-Thinker

我是编程新手,也是 Python 新手。
我写了一个实现 unix 尾部的函数:

def tail(file): 
    strin = open(file, 'r') 
    lis = strin.readlines() 
    lastline = lis[-1] 
    return lastline 
    strin.close() 

但我认为它在性能上不是最优的。
我该如何改进?

请您参考如下方法:

您可以使用 Collections.deque 中的这个食谱

def tail(filename, n=10): 
    'Return the last n lines of a file' 
    return deque(open(filename), n) 

引用这个:- https://docs.python.org/2/library/collections.html#deque-recipes