作者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/cn.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