Python的一些高階學習 2017 08 16

2021-08-06 06:47:42 字數 1144 閱讀 8913

通過迭代器對檔案切片

日常工作中會遇到多達4,5g的日誌檔案,如果把檔案都一次讀到記憶體,再進行切片比較浪費資源:

in [7]: f = open('access.log')

in [7]: lines = f.readlines()

in [7]: lines[1:19]

這樣對文字是可以切片的,但是如果檔案很大,就很浪費資源

可以用迭代器對文字進行切片,這個時候需要用到itertools包下的islice這個函式,

in [7]: from itertools import islice

in [8]: islice?

type: type

string form: docstring:

islice(iterable, [start,] stop [, step]) --> islice object

return an iterator whose next() method returns selected values from an

iterable. if start is specified, will skip all preceding elements;

otherwise, start defaults to zero. step defaults to one. if

specified as another value, step determines how many values are

skipped between successive calls. works like a slice() on a list

but returns an iterator。

這個函式需要乙個可迭代物件, 起始值,終止值, 步進值 ,下面試試看:

in [3]: from itertools import islice

in [4]: islice(lines,100,300)

out[4]: #說明是個可迭代物件

in [5]: for x in islice(lines,100,300):

...: print x

結果是 完美的 成功對文字進行迭代切片

Python的一些高階學習 2017 08 28

最近工作太忙,沒時間寫心得 趁著七夕趕緊來一發 拆分含有多個分隔符的字串 還是經常用到的 兩種方法分割字串 1.split 切分 def mysplit s,ds s 源字串 ds 分隔符 res s for d in ds t map lambda x t.extend x.split d res...

Python的一些高階學習 2017 10 17

如何建立大量的例項節省記憶體 用定義類的slots宣告例項屬性名字的列 直接上比較 class player object def init self,uid,name,status 0,level 1 self.uid uid self.name name self.stat status sel...

一些python高階語法

enum列舉是乙個類。from enum import enum class vip enum green 1 print vip.green.value 通過.value訪問green標籤對應值 name獲取標籤名 列舉型別,列舉名字,列舉值是三個概念 for v in vip print v 遍...