python秘笈
讀入
字串轉陣列
單純轉為陣列
1
2
3
4
5
6
7
8s=input().split()
"""
input:
1 2 3 4
output:
['1','2','3','4']
"""全轉為數字陣列
1
2
3
4
5
6
7
8s=list(map(int,input().split()))
"""
input:
1 2 3 4
output:
[1,2,3,4]
"""
while 輸入
- try大法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15arr=[]
try:
while 1:
arr.append(int(input()))
except:
print(arr)
"""
input:
1
2
3
output:
[1,2,3]
"""
輸出
小數點處理
- format
1
2
3
4
5
6
7flt=3.1415
print("{:.2f}".format(flt))
"""
output:
3.14
"""
陣列
建立空陣列
- 建立一個長度為10的0陣列
1
2
3
4
5
6arr=[0 for i in range(0,10)]
"""
output:
[0,0,0,0,0,0,0,0,0,0]
"""
字典
建立字典
1 | d={1:1,2:2,3:3} |
加入
**TIP!**:d.get(A)
是用來查找字典費是否有A元素,字典在沒有 key 的情況下是無法賦予值的
1 | d={} |