3 回答
TA贡献1998条经验 获得超6个赞
您可以将尾部配方与n = 8的双端队列配合使用。
这将创建一个双头队列,在该队列中,将一个项目添加到末尾(右侧)将有效地从开头(左侧)弹出一个项目,以使长度不超过最大长度:
>>> from collections import deque
>>> deque(range(10000),8)
deque([9992, 9993, 9994, 9995, 9996, 9997, 9998, 9999], maxlen=8)
所述csv.reader对象是一个迭代。将有限长度的双端队列应用到csv阅读器,您就可以开始了:
import csv
from collections import deque
with open('/tmp/trend.csv','rb') as fin:
deq=deque(csv.reader(fin),8)
for sub_list in deq:
print sub_list
以您的10行示例为例,将输出:
['2013-06-25 20:06', '8']
['2013-06-26 20:06', '7']
['2013-06-26 20:06', '6']
['2013-06-26 20:06', '5']
['2013-06-26 20:06', '4']
['2013-06-26 20:06', '3']
['2013-06-26 20:06', '2']
['2013-06-26 20:08', '1']
TA贡献1844条经验 获得超8个赞
import csv
# Open the file with a "with" statement to provide automatic cleanup
# in case of exceptions.
with open("trend.csv","rb") as file:
cr = csv.reader(file)
lines = [row for row in cr]
# Use slice notation and the wonderful fact that python treats
# negative indices intelligently!
for line in lines[-8:]:
print line
添加回答
举报