精通PYTHON 30 DAYS — DAY 4

第三章 — Py填充:串列、Tuple、字典與集合

這邊是剩下的字典與集合的用法語介紹:

dictionary

{}組成,一連串的key/value pair,字典的鍵是獨一無二的
ex:

{ 
"abc" : "a string",
"another" : "another string",
"QQ" : "others",
"number111" : 1
}

也可以用類似陣列方式去添加新的key/value pair、取得值
ex:

a_dict = { 
"abc" : "a string",
"another" : "another string",
"QQ" : "others",
"number111" : 1,
0 : "it's fine when index is number"
}
a_dict["GG3b0"] = "another new string"
print(a_dict) # 印出
{
"abc" : "a string",
"another" : "another string",
"QQ" : "others",
"number111" : 1,
0 : "it's fine when index is number",
"GG3b0" : "another new string"
}
print(a_dict[QQ]) # 印出"others"

修改鍵的值

>>> a_dict["QQ"] = "changed"
>>> a_dict
{
"abc" : "a string",
"another" : "another string",
"QQ" : "changed",
"number111" : 1,
0 : "it's fine when index is number",
"GG3b0" : "another new string"
}

但是不可以像list一樣使用位置取值
ex:

a_dict[0]  // error!!!!

使用dict建立字典,在字典裏面鍵的順序是任意的

>>> lol = [ ['a', 'b'], ['c', 'd'], ['e', 'f'] ]
>>> dict(lol)
{
'c':'d',
'a':'b',
'e':'f'
}
  • update() : 合併字典
  • del : 刪除項目
  • clear() : 刪除所有項目
  • in : 測試鍵是否存在
  • keys() : 取得所有的鍵
  • values() : 取得所有的值
  • items() : 取得所有的鍵值配對
  • copy() : 複製
>>> dict1 = {
>>> 'a' : 45,
>>> 'A' : 65
>>> }
>>>
>>> dict2 = {
>>> 'b' : 46,
>>> 'B' : 66
>>> }
>>>
>>> dict1.update(dict2)
>>> dict1
{'a': 45, 'A': 65, 'b': 46, 'B': 66}
>>>
>>> # 若兩個字典有重複的鍵,update裡面的勝出
>>> first = { 'a':1 , 'b':2 }
>>> second = { 'b':'second' }
>>> first.update(second)
>>> first
{ 'a':1 , 'b':'second' }
>>>
>>> del first['b']
>>> first
{ 'a':1 }
>>>
>>> first.clear()
>>> first
{}
>>>
>>> new_dict = {
>>> 'a' : 1,
>>> 'b' : 2,
>>> 'c' : 3
>>> }
>>> 'A' in new_dict
False
>>> 'a' in new_dict
True
>>>
>>> signals = {'green':'go','yellow':'go faster','red':'smile for the camera'}
>>> signals.keys()
dict_keys(['green', 'yellow', 'red'])
>>> # 用list將回傳的結果轉成串列
>>> list(signals.keys())
['green', 'yellow', 'red']
>>> list(signals.values())
['go', 'go faster', 'smile for the camera']
>>> list(signals.items())
[('green', 'go'), ('yellow', 'go faster'), ('red', 'smile for the camera')]
>>>
>>> signals
{'green': 'go', 'yellow': 'go faster', 'red': 'smile for the camera'}
>>> new_signals = signals.copy()
>>> signals['red'] = 'XDDDD'
>>> signals
{'green': 'go', 'yellow': 'go faster', 'red': 'XDDDD'}
>>> new_signals
{'green': 'go', 'yellow': 'go faster', 'red': 'smile for the camera'}

用鍵來取得一個項目,避免鍵不存在而噴出error,有兩種方法:

  1. 一開始先使用in來測試
  2. 使用get(),如果該值存在即可得到,否則得到None
>>> # 1
>>> 'Marx' in pythons
>>> False
>>> # 2
>>> pythons.get('Cleese')
>>> 'John'
>>> pythons.get('Marx')
>>> None

Set

可以把集合想像成被移除值,只留下鍵值的字典,每個鍵都必須要獨一無二的。

建立集合

>>> empty_set = set()
>>> empty_set
set()
>>> even_numbers = { 0, 2, 4, 6, 8 }
>>> even_numbers
{ 0, 2, 4, 6, 8 }

用Set轉換其他類型

>>> # 把list變成集合
>>> set(['Dasher','Dancer','Prancer','Mason-Dixon'])
{'Prancer', 'Mason-Dixon', 'Dancer', 'Dasher'}
>>> # 把tuple變成集合
...
>>> set(('Ummagumma','Echoes','Atom Heart Mother'))
{'Ummagumma', 'Atom Heart Mother', 'Echoes'}
>>> # 若把字典變成集合,只會用到鍵
...
>>> set({'apple':'red','orange':'oreange','cherry':'red'})
{'apple', 'cherry', 'orange'}

集合運算子

# 交集 & intersection()
>>> a = {1, 2}
>>> b = {2, 3}
>>> a & b
{2}
>>> a.intersection(b)
{2}
# 聯集 | union()
>>> a | b
{1, 2, 3}
>>> a.union(b)
{1, 2, 3}
# 差集 - difference()
>>> a - b
{1}
>>> a.difference(b)
{1}
# 互斥 ^ symmetric_difference()
>>> a ^ b
{1, 3}
>>> a.symmetric_difference(b)
{1, 3}
# 檢查是否為另一個的子集合 <=
>>> a <= b
False
>>> a.issubset(b)
False
# 真子集 < (第二個集合必須擁有第一個集合的所有成員)
>>> a < b
False
# 超集合 > issuperset() (跟真集合相反,第二個集合的成員都是第一個集合的成員)
>>> a >= b
False
>>> a.issuperset(b)
False
# 真超集合 >
>>> a > b
False
Show your support

Clapping shows how much you appreciated yysu’s story.