2

# 變數型態- dict: 就是查資料的字典

python的`dict`由一組`key:value`組成放在大括號裡，

``````D = {'s':"黑桃", 'h':"紅心", 'd':"方塊", 'c':"梅花"}
``````

``````>>> D['s']
'黑桃'
>>> D['d']
'方塊'
``````

``````pocket = ['任意門', '縮小燈', '時光機']
print(pocket[1])
``````

# 變數型態- set: 像是數學上講的集合

• 放在集合裡面的元素順序不重要
• 放在集合內的元素不會重複
例如說宣告`{1,2,3}``{2,3,1}``{1,1,2,2,3}`指的全部都是同一個集合

• key值的順序不重要
• key值不會重複

`==`判斷會將兩本字典視為相同內容(比較: 若是列表與元組的元素順序不同即視為不同)

``````D1 = {'s':"黑桃", 'h':"紅心", 'd':"方塊", 'c':"梅花"}
D2 = {'d':"方塊", 'c':"梅花", 's':"黑桃", 'h':"紅心"}
print(D1 == D2) # True
``````

``````s1 = {1,2,3}
s2 = {2,3,1}
s3 = {1,1,2,2,3}
print(s1 == s2) # True
print(s2 == s3) # True
print(s3) # {1, 2, 3}
``````

## 集合運用: 去除列表中重複的元素

``````def removeDuplicate(seq):
return sorted(set(seq), key = seq.index)

mylist = removeDuplicate(["a", "b", "a", "c", "c"])
print(mylist) #["a", "b", "c"]
``````

# 快速查找元素

``````import timeit
List = list(range(10000))
Set = set(range(10000))
print(timeit.timeit('9999 in List', number=10000, globals=globals()))
print(timeit.timeit('9999 in Set', number=10000, globals=globals()))
``````

``````0.8512682000000069
0.0004332000000033531
``````