close
使用環境: Python 3.5.2
1. 存取字典檔
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 建置空的 dictionary | |
dict = {} | |
#加入值為array的資料 | |
dict['array'] = [1,2,3,4,5] | |
#印出剛剛加入的資料 | |
print("Result: ", dict['array']) | |
#Result: [1, 2, 3, 4, 5] | |
#加入值為字串的資料 | |
dict['str'] = "str" | |
#印出所有 dictionary 內的資料 | |
#只印出values部分 | |
for value in dict.values(): | |
print("Result:", value) | |
# Result: str | |
# Result: [1, 2, 3, 4, 5] | |
#印出 key, value pair | |
for key in dict.keys(): | |
print("Result: ", key, " ", dict[key]) | |
# Result: array [1, 2, 3, 4, 5] | |
# Result: str str |
2. 存取陣列
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#建立空的Array | |
arr = [] | |
#加入元素 | |
arr.append("str") | |
arr.append(3) | |
arr.append(-1) | |
#印出array中所有值 | |
print("Result: ",arr) | |
#Result: ['str', 3, -1] | |
#印出特定index的值 | |
print("Result: ", arr[0]) | |
#Result: str | |
#矩陣長度 | |
print("Result: ",len(arr)) | |
# Result: 3 |
3. 存取矩陣
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#建立二為矩陣並且初始化為0矩陣 | |
# 0, 0, 0, 0, 0 | |
# 0, 0, 0, 0, 0 | |
# 0, 0, 0, 0, 0 | |
row = 3 | |
column = 5 | |
m = [[0 for x in range(column)] for y in range(row)] | |
#讀取矩陣 | |
for y in range(row): | |
for x in range(column): | |
print(y, " - ", x, " : ", m[y][x]) | |
# 0 - 0 : 0 | |
# 0 - 1 : 0 | |
# 0 - 2 : 0 | |
# 0 - 3 : 0 | |
# 0 - 4 : 0 | |
# 1 - 0 : 0 | |
# 1 - 1 : 0 | |
# 1 - 2 : 0 | |
# 1 - 3 : 0 | |
# 1 - 4 : 0 | |
# 2 - 0 : 0 | |
# 2 - 1 : 0 | |
# 2 - 2 : 0 | |
# 2 - 3 : 0 | |
# 2 - 4 : 0 | |
#增加第0列元素 | |
m[0].append(10) | |
#讀取矩陣 | |
print("Result: ",m) | |
# Result: [[0, 0, 0, 0, 0, 10], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] |
4. 字典轉換成陣列或矩陣
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#建立2x3矩陣 | |
a = [[1,2,3],[4,5,6]] | |
print("Result: ",a) | |
# Result: [[1, 2, 3], [4, 5, 6]] | |
#將 2x3 矩陣轉換成 dictionary, 並以每一個 row 的第一個值當成 key, 其餘為 value | |
print("Matrix transforms into Dictionary") | |
trans2dict = dict((x[0], (x[1],x[2])) for x in a[0:]) | |
print("Result: ", trans2dict) | |
# Result: {1: (2, 3), 4: (5, 6)} |
全站熱搜