Python培訓知識總結系列- 第二章Python數據結構第三部分-字典,集合
阿新 • • 發佈:2018-01-27
而是 結構 move 原子 返回 總結 刪除 添加元素 pen 編寫一個函數 remove_duplicates,該函數將列表作為參數,並返回一個包含源列表中唯一元素的新列表。新列表中未重復出現的元素可采用任何順序。
target=[]
def remove_duplicates(list):
for each in list:
if each not in target:
target.append(each)
return target
print(elements[‘lithium‘])
3
target=[]
def remove_duplicates(list):
for each in list:
if each not in target:
target.append(each)
return target
集合是唯一元素的集合,沒有任何特定的排序。我們可以從這樣的列表中創建一個集合:
country_ set = set(countries)
len(country_set)
196
添加元素到集合
country_set.add("Florin")
集合也有一個與列表一樣的 pop 方法。從集合 pop 一個元素時,一個隨機元素被刪除(記住,集合不同於列表,是無序的,所以沒有 "最後一個元素"。
。字典不像列表和集合存儲單個對象,而是存儲元素對:鍵(Key) 和 值(Value)。我們在該示例中定義了一個字典,其中鍵是元素名稱,值是它們對應的原子序數。
elements = {‘hydrogen‘: 1, ‘helium‘: 2, ‘carbon‘: 6}
可以用方括號括住鍵來查找字典中的值:
print(elements[‘carbon‘])
6
也可以使用方括號將新值插入字典:
elements[‘lithium‘] = 3
3
Python培訓知識總結系列- 第二章Python數據結構第三部分-字典,集合