作者bigpigbigpig (To littlepig with love)
看板Python
標題Re: [問題] File1內容跳一行再加File2內容
時間Fri Apr 17 11:10:19 2015
※ 引述《Dong0129 (阿東)》之銘言:
: 請問各位版友,
: 我有兩個檔案,
: File1: File2:
: 1 5
: 2 6
: 3 7
: 4 8
: 要合併成:
: File3:
: 1 5
: 2 6
: 3 7
: 4 8
: 目前的code:
: rfd1=open("file1","r")
: rfd2=open("file2","r")
: wfd=open("file3","w")
: for i in rfd1:
: if i[-1]=='\n':
: i=[0:-1]
: wfd.write(i)
: for i in rfd2:
: wfd.write('\t'+i)
: break
: rfd1.close()
: rfd2.close()
: wfd.close()
: 目前想出來也可用的程式碼如上,
: 但在思考是否有更好更短的寫法呢??
: 還算是python初學者...所以寫的不夠好請見諒!!
Python 3 :
fi_1 = open('file1','r')
fi_2 = open('file2','r')
lines_1 = fi_1.readlines()
lines_2 = fi_2.readlines()
fi_1.close()
fi_2.close()
fo_1 = open('file3','w')
for L1, L2 in zip(lines_1, lines_2):
print(L1.strip() + '\t' + L2.strip(), file = fo_1)
fo_1.close()
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.25.191.8
※ 文章網址: https://webptt.com/m.aspx?n=bbs/Python/M.1429240221.A.5FD.html
※ 編輯: bigpigbigpig (114.25.191.8), 04/17/2015 11:27:41
※ 編輯: bigpigbigpig (114.25.191.8), 04/17/2015 11:29:56
※ 編輯: bigpigbigpig (114.25.191.8), 04/17/2015 11:30:29
1F:推 Dong0129: 之前在別人的程式碼裡也看過zipㄟ, 04/17 11:49
2F:→ Dong0129: 請問專門做字串的結合的指令嗎? 04/17 11:49
zip 可以把兩個 list: L1 和 L2 「黏」起來,
L1 的第一個元素對應 L2 的第一個元素,
L1 的第二個元素對應 L2 的第二個元素,
依此類推...
以下是 Pascal 三角形的 Python 3 程式碼:
def next_Pascal(L):
nL1 = [ 0 ] + L
nL2 = L + [ 0 ]
return [ x+y for x, y in zip(nL1, nL2) ]
def Pascal_triangle(n):
R = list()
L1 = [ 1 ]
for i in range(n+1):
R.append(L1)
L1 = next_Pascal(L1)
return R
Pascal_10 = Pascal_triangle(10)
for item in Pascal_10: print(item)
=======================================
執行結果:
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
[1, 6, 15, 20, 15, 6, 1]
[1, 7, 21, 35, 35, 21, 7, 1]
[1, 8, 28, 56, 70, 56, 28, 8, 1]
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
[1, 10, 45, 120, 210, 252, 210, 120, 45, 10, 1]
※ 編輯: bigpigbigpig (114.25.191.8), 04/17/2015 12:36:50
3F:推 Conjuror: 用 with open 應該可以再精簡一點,還不用管 close 04/17 14:34
4F:推 Dong0129: 請問可以示範with open的寫法並稍做講解嗎? 04/17 14:49
※ 編輯: bigpigbigpig (114.25.176.10), 04/20/2015 09:23:40