[問題] 幫忙解釋一下這幾行程式

看板Python作者 (阿東)時間10年前 (2015/04/20 22:24), 10年前編輯推噓3(302)
留言5則, 2人參與, 最新討論串1/1
各位版友好, 之前在網路上找到一段程式碼, 但是我看不太懂它作業的過程, 能否請教版友是否能夠解釋呢? file1: 1 2 3 file2: 1>2 2>3 ... 這支程式是能夠將file1裡的資料重新整理成file2的資料, def joinlns(lns,spliter=","): return spliter.join([ln.strip() for ln in lns]) lines=open(file1).readlines() mergedlines=[joinlns(x,spliter)=">"] for x in zip(lines[::1],lines[1::1]) with open(file2,'a') as handle: handle.write('\n'.join(mergedlines)+'\n') 程式碼如上... 另外想額外請教,在讀python的過程裡看到時常用[:]這種用法描述字串的變動, 請問能夠稍微講解一下嗎?或是有關鍵字能夠找到相關的教學呢? -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 220.137.113.177 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1429539890.A.7D8.html ※ 編輯: Dong0129 (220.137.113.177), 04/20/2015 22:25:13

04/20 22:58, , 1F
"12345"[:] => "12345", "12345"[1:5] => "2345"
04/20 22:58, 1F

04/20 22:59, , 2F
"12345"[1:5:2] => "24"
04/20 22:59, 2F

04/20 23:01, , 3F
簡單說就是: [從這個索引:到這個索引減1:一次跳幾個]
04/20 23:01, 3F

04/20 23:15, , 4F
畫個圖會更容易瞭解,這也是 zip 最漂亮的用法之一
04/20 23:15, 4F

04/20 23:26, , 5F
[start:end:step]=> python slicing operator
04/20 23:26, 5F
文章代碼(AID): #1LDGmoVO (Python)
文章代碼(AID): #1LDGmoVO (Python)