2月份開始我的python學習之路。希望借助簡書記錄我學習的點滴舞丛。
1耘子,字符串格式化:
"%s can be %s" % ("strings", "interpolated")
"{0} can be {1}".format("strings", "formatted")
可以使用關(guān)鍵字(變量)來對格式化的鍵值賦值:?
"{name} wants to eat {food}".format(name="Bob", food="lasagna")
不要使用相等符號`==`來把對象和 None 進行比較,而要用 `is`球切。
None的第一個字母要大寫谷誓!?
2,元組很像列表吨凑,但它是“不可變”的捍歪。
tup = (1, 2, 3)
tup[0] = 3 ?#拋出一個類型錯誤
len(tup) #=> 3
tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6)
tup[:2] #=> (1, 2)
2 in tup #=> True
#你可以把元組(或列表)中的元素解包賦值給多個變量
a, b, c = (1, 2, 3)? # a is now 1, b is now 2 and c is now 3
#如果你省去了小括號,那么元組會被自動創(chuàng)建
d, e, f = 4, 5, 6
e, d = d, e???# d is now 5 and e is now 4
3鸵钝,字典用于存儲映射關(guān)系
empty_dict = {}
filled_dict = {"one": 1, "two": 2, "three": 3}
#使用 [] 來查詢鍵值
filled_dict["one"] #=> 1
#將字典的所有鍵名獲取為一個列表
filled_dict.keys() #=> ["three", "two", "one"]
要使用get方法來避免鍵名錯誤
filled_dict.get("one") #=> 1
filled_dict.get("four") #=> None
# get方法支持傳入一個默認值參數(shù)糙臼,將在取不到值時返回。
filled_dict.get("one", 4) #=> 1
filled_dict.get("four", 4) #=> 4
# Setdefault方法可以安全地把新的名值對添加到字典里
filled_dict.setdefault("five", 5) ? ? ? ??#filled_dict["five"]被設(shè)置為 5
filled_dict.setdefault("five", 6) ? ? ? ?#filled_dict["five"]仍然為 5
4蒋伦,使用一堆值來初始化一個集合
some_set = set([1,2,2,3,4]) ? ? ? ? ? ??# some_set現(xiàn)在是 set([1, 2, 3, 4])
#從 Python 2.7 開始弓摘,{} 可以用來聲明一個集合
filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4}
# ?集合是種無序不重復的元素集,因此重復的 2 被濾除了痕届。{} 不會創(chuàng)建一個空集合韧献,只會創(chuàng)建一個空字典末患。
#把更多的元素添加進一個集合
filled_set.add(5) ? ? ? ? ??# filled_set現(xiàn)在是 {1, 2, 3, 4, 5}
#使用 & 來獲取交集
other_set = {3, 4, 5, 6}
filled_set & other_set #=> {3, 4, 5}
#使用 | 來獲取并集
filled_set | other_set #=> {1, 2, 3, 4, 5, 6}
#使用 - 來獲取補集