python學習11-集合和字典

集合:創立的一組無序,但是所有元素只出現一次的元素集合

ten=set(range(10))
lows=set([0,1,2,3,4])
odds=set([1,3,5,7,9])
lows.add(9)              #在lows後面加上9
lows.difference(odds)    #lows減去odds
lows.issubset(ten)      #lows是ten的子集?答案是true
lows.issuperset(odds)    #答案是false,判斷一個自己包含另一個子集否?
lows.remove(0)            #移除第一個元素
lows.symmetric_difference(odds)   #根據不再兩個集合中的元素創立新的集合
lows.union(odds)                    #根據兩個集合中所有元素,創建一個新的集合
lows.clear()                      #清楚所有元素
lows

注意用set()來設置值!

2.散列表hash

hash(123)  #123
hash('good')   #-753937853
hash('ture')

值得注意的是:散列碼是通過對值得計算得到,所以,當某列表內容發生變化的時候,其散列碼也會發生相應的變化。正因爲這樣,python只允許集合含有不變量。
當然,布爾值、數字、字符串和數組也是可以應用的。

3.字典

#字典就是給一個索引,對應一個值,如同電話簿,給名字對應一個號碼,因此提供查詢功能
birds={'canada goose':3,'northern fulmar':11,'chinese monkey':55}   #定義了一個字典birds
#birds
#birds['canada goose']           #輸出3
#注意如果字典中沒有,就會報錯,如同數組越界錯誤一樣。
#if 'canada goose'  in birds:   #用來查詢是否在字典中
#    print "have"
#else
#    print "donnot have!"

#在字典中刪除某個條目,用del d[k]
"""
del birds['canada goose']
birds
"""
#x循環
for x in birds:
    print x,birds[x]       #這裏可以看出,列表的x是數值,而字典的x是鍵值,並且他的輸出是無序的,並非從第一個到最後一個

#字典的內置函數
scientists={'Newton':1642,'Darwin':1809,'Turing':1912}
print 'keys:',scientists.keys()         #輸出鍵值,如Newton,Darwin,Turing
print 'values',scientists.values()      #鍵值對應的值
print 'items',scientists.items()        #輸出鍵值和對應的值
print 'get',scientists.get('Curie',1867)    #查找字典中Curie對應的值,如果沒有默認爲1867
temp={'Curie':1867,'Hopper':1906,'Franklin':1920}
scientists.update(temp)              #將temp加入到scitists的字典裏面
print "after update:",scientists

scientists.clear()                     #清除字典裏面的數
print 'after clear:',scientists

#輸出結果爲:
"""
northern fulmar 11
chinese monkey 55
canada goose 3
keys: ['Turing', 'Newton', 'Darwin']
values [1912, 1642, 1809]
items [('Turing', 1912), ('Newton', 1642), ('Darwin', 1809)]
get 1867
after update: {'Curie': 1867, 'Darwin': 1809, 'Franklin': 1920, 'Turing': 1912, 'Newton': 1642, 'Hopper': 1906}
after clear: {}
"""
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章