python學習筆記16:tuple, set, dictionary

1. Tuples

tuples和lists很相似,但是它們的元素是固定的,一旦一個tuple被創建,那麼就不能執行添加元素、刪除元素、修改元素、或者對元素進行排序等操作(但注意可以對一個tuple重新賦值)。看到這裏,不禁會疑問,既然tuple什麼都不能做,幹嘛還要用它,tuple的存在可能基於兩個原因:1)在python中,它比list操作速度更快,如果我們定義一個常量集,不需要修改,只需要遍歷,則最好用tuple;2)安全性:由於tuple不能進行修改,那麼對於這種類型的數據,tuple可以避免數據被偶然修改。

tuple用()創建,可以直接創建,如t1 = (1,3,5); 也可以從list創建,如t2 = tuple([2 * x for x in range(1,5)]); 另外還可以從string創建,如t3 = tuple("abcd") # t3: ('a','b','c','d')。

同時tuple也可以進行len(),max(),min(),sum(),index(),slicing等操作。如下所示:

tuple1 = ("green","red","blue")
tuple2 = tuple([7,1,2,23,4,5])
print (len(tuple2)) # 6
print (max(tuple2)) # 23
print (min(tuple2)) # 1
print (sum(tuple2)) # 42
print (tuple2[0])   # 7
tuple3 = 2 * tuple1
print (tuple3)     # ('green', 'red', 'blue', 'green', 'red', 'blue')
print (tuple2[2:4]) # (2, 23)
print (tuple1[-1])  # blue
for v in tuple1:
    print (v,end=' ')   # green red blue
print ()
print (tuple1==tuple2)   # False

2. Sets

Set和list也有相似之處,可以用來存儲數據,但和list有三點不同:1)set中無重複元組,這可以用來做很多事情,如在decision tree的程序中,用來取某一屬性上的所有值,則可以在取得屬性上值的list後,做set(list)操作,則去除了重複值; 2)set和list與tuple不同,它是無序的,所以如果你所需要存儲的數據不需要順序,則用set會比list要高效。3)另外,set中的元素必須是可hash的,而list卻沒有這個要求,目前爲止除了list,其它類型都是必須可hash的。

set的創建用{}表示,也可以用set()構造函數創建,如set1 = {1,3,5}; set2 = set([2*x for x in range(1,5)]); set3 = set("abcd")。

set的操作函數:

add(e):添加一個元素e;

remove(e):刪除一個元素e;

max(),min(),len(),sum():常用的幾種操作;

s1.issubset(s2):判斷s1是否是s2的子集;

s1.issuperset(s2):判斷s1是否是s2的父集;

==,!=:判斷兩集合是否相同;

<, <=, >, >=:判斷子集與父集;

s1.union(s2)或者|:兩集合的並;

s1.intersection(s2)或者&:兩集合的交;

s1.difference(s2)或者-:兩集合的差。

s1.symmetric_difference(s2)或者^:兩集合的異或。

下面對上面的函數舉個小例子:

s1 = {1,2,4}
s1.add(6)
print (s1)        # {1,2,4,6}
print (len(s1))   # 4
print (max(s1))   # 6
print (min(s1))   # 1
print (sum(s1))   # 13
print (3 in s1)   # False
s1.remove(4)  
print (s1)        # {1,2,6}

s1 = {1,2,4}
s2 = {1,4,5,2,6}
print (s1.issubset(s2))    # True
print (s2.issuperset(s1))  # True
print (s1==s2)             # False
print (s1<=s2)             # True

print (s1.union(s2))       # {1,2,4,5,6}
print (s1|s2)              # {1,2,4,5,6}

print (s1.intersection(s2))# {1,2,4}
print (s1&s2)              # {1,2,4}

print (s1.difference(s2))  # set()
print (s1-s2)              # set()

print (s1.symmetric_difference(s2))  # {5,6}
print (s1^s2)                        # {5,6}

set 在in 和not in以及在remove()操作上比list要高效。

3. Dictionary

dictionary是採用鍵值對來對數據進行存儲,它可以很快的實現基於key的檢索,刪除,更新等操作。key很像索引,也必須是可hash的。並且,dictionary中不能包含相同的key值。

dictionary的創建也是用{},和set相同,所以,默認情況下,我們創建set的時候採用set(),而把{}留給dictionary,比如student={},我們可以默認是創建dictionary的;創建的例子:

students = {"111-58-5858": "John", "132-59-5959": "Peter"}

dictionary的一些函數操作:

add : 可以用dictionaryName[key] = value來操作; 如果這個key已經在dictionary中存在了,那麼則進行修改操作;而且,我們可以用dictionaryName[key]來讀取某個item值;

delete:用del dictionaryName[key]做刪除操作;

loops:用for key in students: 這種形式做循環操作;

len():返回dictionary的大小,共有多少個鍵值對;

in :查看某key是否在dictionary中;

==:判斷兩dictionary是否包含相同的內容;

keys():返回dictionary中的所有key;

values():返回所有的值;

items():返回所有的內容,以鍵值對的tuple形式顯示;

clear():刪除所有內容;

get(key):獲取鍵爲key的值;

pop(key):刪除鍵爲key的項,並返回其值;

popitem():隨機刪除一個項,並返回其內容;

下面對這些函數舉簡單例子:

students = {"111-58-5858":"John", "132-59-5959":"Peter"}

# add
students["234-56-9010"] = "Susan"
# modify
students["111-58-5858"] = "Smith"
# 檢索
print (students["111-58-5858"])    # Smith
# 刪除
del students["234-56-9010"]
# 循環
for key in students:
    print (key + ":" + students[key])    # 111-58-5858:Smith  132-59-5959:Peter
# len
print (len(students))  # 2
# in, not in 
print ("111-58-5858" in students)  # True
print ("111" not in students)      # True
# ==, !=
d1 = {"red":22, "blue":2}
d2 = {"blue":2, "red":22}
print (d1==d2)   # True
print (d1!=d2)   # False

#keys()
print (tuple(students.keys()))   # ('111-58-5858', '132-59-5959')
print (tuple(students.values())) # ('Smith', 'Peter')
print (tuple(students.items()))  # (('111-58-5858', 'Smith'), ('132-59-5959', 'Peter'))
print (students.get("111-58-5858"))  # Smith
print (students.pop("111-58-5858"))  # Smith
print (students.popitem())           # ('132-59-5959', 'Peter')




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章