在 python 中沒有陣列,一般都是用 dictionary 這種東西來取代之
每次都很容易搞混這兩個東西,這篇文章把它們兩個的指令好好整理一下
List 部份(順序固定)
# 起始化 list
L1= {‘I’:1,’II’:2,’III’:3,’IV’:4,’V’:5,’VI’:6,’VII’:7,’VIII’:8,’IX’:9}
# value list 值可以排序,但字典不行
L1.sort()
#插入一個值
L1.append(‘value’)
#在指定位置插不一個值
L1.insert (index,’value’)
#移除一個值
L:1.remove(‘value’)
Dictionary 部份(順序不固定)
# 建立一個空白的字典
D1 = {}
# 顯示字典
print D1
# 顯示字典長度
print "Length = ", len(D1)
# 增加新的 key 與其相對應的 value
D1['0'] = ‘zero’
D1['1'] = ‘one’
D1['2'] = ‘two’
D1['3'] = ‘three’
D1['4'] = ‘four’
# 從 key 找到其相對應的 value
print "The english word for drei is ", D1['1']
# 更直覺的方式從 key 找到 value
if 1in D1:
print "The english word for drei is ", D1[1]
# key list 值可以排序,但字典不行
L2 = D1.keys()
L2.sort()
# copy 一個字典 (但順序不一定相同)
D2 = D1.copy()
# 刪除一筆紀錄
del D2['1']
# 取出某個值的同時刪除這筆紀錄
e3 = D2.pop(‘drei’)
#存取字典與檔案
import pickle
print romanD
file = open("roman1.dat", "w")
pickle.dump(romanD1, file)
file.close()
file = open("roman1.dat", "r")
romanD2 = pickle.load(file)
file.close()
print "Dictionary after pickle.dump() and pickle.load():"
print romanD2
List 與 Dictionary 互相轉換部份
#插入一個 list 的值進入 dictionary, index 名稱自行指定
L1={ }
Li = [1,2,3,4,5]
L1[index] = Li
# 取出 Ditionary 裡的值,是一個 list
L1 = D1.values()
# 將 dictionary 切割成兩個 list
romanD = {‘I’:1,’II’:2,’III’:3,’IV’:4,’V’:5,’VI’:6,’VII’:7,’VIII’:8,’IX’:9}
romankeyList = []
romanvalueList = []
for key, value in romanD.items():
romankeyList.append(key)
romanvalueList.append(value)
# 從兩個list 合併成為一個 dictionary
romanD1 = dict(zip(romankeyList, romanvalueList))
相關閱讀
python tutorial – list
xperimenting with Dictionaries (Python)
Python List, Python Tuple, Python Dictionary