推 Dong0129: 之前在別人的程式碼裡也看過zipㄟ, 04/17 11:49
→ 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
推 Conjuror: 用 with open 應該可以再精簡一點,還不用管 close 04/17 14:34
推 Dong0129: 請問可以示範with open的寫法並稍做講解嗎? 04/17 14:49
※ 編輯: bigpigbigpig (114.25.176.10), 04/20/2015 09:23:40