# python常用程式片段
## 如何加入一元素在二維串列
```python=1
row = eval(input()) #輸入列數
column = eval(input()) #輸入欄數
lst=[] #建立空串列
for i in range(row): #外迴圈控制列數
lst.append([]) #新增一列
for j in range(column): #內迴圈控制欄數
lst[i].append(i+j) #新增資料元素到每一欄中
#((i+j)是(列+欄)索引值)
```

<iframe width="800" height="500" frameborder="0" src="https://pythontutor.com/iframe-embed.html#code=row%20%3D%20int%28input%28%29%29%0Acolumn%20%3D%20int%28input%28%29%29%0Alst%3D%5B%5D%0Afor%20i%20in%20range%28row%29%3A%0A%20%20%20%20lst.append%28%5B%5D%29%0A%20%20%20%20for%20j%20in%20range%28column%29%3A%0A%20%20%20%20%20%20%20%20lst%5Bi%5D.append%28i%2Bj%29&codeDivHeight=400&codeDivWidth=350&cumulative=false&curInstr=0&heapPrimitives=nevernest&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false"> </iframe>
---
## 如何依順序列印二維串列-第1種方法
```python=1
lst=[[1,2,3],[2,3,4]] #建立二維陣列lst
for i in range(len(lst)): #len(lst) 取得總列數(row)
for j in range(len(lst[i])): #len(lst[i]) 取得第i列的總欄數
print("%4d" %lst[i][j],end="") #印出[列i、欄j]的元素資料,end=""表示不換列
print() #換列
```

<iframe width="800" height="500" frameborder="0" src="https://pythontutor.com/iframe-embed.html#code=lst%3D%5B%5B1,2,3%5D,%5B2,3,4%5D%5D%0A%0Afor%20i%20in%20range%28len%28lst%29%29%3A%0A%20%20%20%20for%20j%20in%20range%28len%28lst%5Bi%5D%29%29%3A%0A%20%20%20%20%20%20%20%20print%28%22%254d%22%20%25lst%5Bi%5D%5Bj%5D,end%3D%22%22%29%0A%20%20%20%20print%28%29&codeDivHeight=400&codeDivWidth=350&cumulative=false&curInstr=0&heapPrimitives=nevernest&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false"> </iframe>
---
## 如何依順序列印二維串列-第2種方法
```python=1
lst=[[1,2,3],[2,3,4]] #建立二維串列lst
for row in lst: #len(lst) 依序讀取二維串列lst的每一列至row一維串列
for value in row: #依序讀取一維串列row的值至value變數
print("%4d" %value,end="") #印出value變數值,end=""表示不換列
print() #換列
```

<iframe width="800" height="500" frameborder="0" src="https://pythontutor.com/iframe-embed.html#code=lst%3D%5B%5B1,2,3%5D,%5B2,3,4%5D%5D%20%0A%0Afor%20row%20in%20lst%3A%20%20%20%20%20%20%20%20%20%20%20%20%0A%20%20%20%20for%20value%20in%20row%3A%20%0A%20%20%20%20%20%20%20%20print%28%22%254d%22%20%25value,end%3D%22%22%29%0A%20%20%20%20print%28%29&codeDivHeight=400&codeDivWidth=350&cumulative=false&curInstr=0&heapPrimitives=nevernest&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false"> </iframe>
---
## 如何取得2維陣列的列數與欄數
```python=1
lst = [[1,2,3],[2,3,4]]
print (lst)
print (lst[0])
print (len(lst2))
print (len(lst[0]))
```

---