我從兩年前接觸python,到現(xiàn)在python已經(jīng)陪伴我渡過了我的大半個職業(yè)生涯,用過Django開發(fā)個人博客,用過pandas、numpy做過數(shù)據(jù)分析,還用過scikit-learn的數(shù)據(jù)挖掘算法,還使用過spider寫爬蟲,但是種種過往在腦中好似一場云煙,經(jīng)歷過卻什么都沒留下,所以從頭開始梳理,將Python的相關(guān)知識點一一記錄下來。
我一直使用的是經(jīng)典2.7,官方稱2020后將停止對2.x的維護,但是我還是習(xí)慣使用2.7版本。另外可以使用from __future__ import module
這種形式在2.x中使用3.x的方法。
# 使用數(shù)字符號可以注釋單行.""" 強調(diào)內(nèi)容多行注釋可以使用三個 """"
# 你的數(shù)字3 # => 3# 簡單的數(shù)學(xué)計算1 + 1 # => 28 - 1 # => 710 * 2 # => 2035 / 5 # => 7# 除法相對來說有點麻煩,因為除法的結(jié)果是整數(shù)還是浮點數(shù)是自動的。5 / 2 # => 2# 為了解決除法,我們需要了解浮點數(shù).2.0 # 這就是一個浮點數(shù)11.0 / 4.0 # => 2.75 啊哈哈...是不是好多了# 整除的結(jié)果無論是正數(shù)還是負(fù)數(shù)都會截斷.5 // 3 # => 15.0 // 3.0 # => 1.0 # works on floats too-5 // 3 # => -2-5.0 // 3.0 # => -2.0# 注意我們可以通過導(dǎo)入模塊的方式使用一個/就進行正常的除法.from __future__ import division11 / 4 # => 2.75 ...normal division11 // 4 # => 2 ...floored division# 模的操作7 % 3 # => 1# 求冪2 ** 4 # => 16# 使用括號強制定義優(yōu)先級(1 + 3) * 2 # => 8# 布爾操作# 注意 "and" 和"or" 是要區(qū)分大小寫的True and False # => FalseFalse or True # => True# 注意用整數(shù)進行布爾操作0 and 2 # => 0-5 or 0 # => -50 == False # => True2 == True # => False1 == True # => True# 用not來否定not True # => Falsenot False # => True# 等于是 ==1 == 1 # => True2 == 1 # => False# 不相等是 !=1 != 1 # => False2 != 1 # => True# 更多的比較1 < 10 # => True1 > 10 # => False2 <= 2 # => True2 >= 2 # => True# 可以進行一串比較!1 < 2 < 3 # => True2 < 3 < 2 # => False# 可以使用 " 或 '來創(chuàng)造字符串"This is a string."'This is also a string.'# 字符串還可以進行相加,代表拼接!"Hello " + "world!" # => "Hello world!"# 沒有 '+' 也可以進行拼接"Hello " "world!" # => "Hello world!"# 增加更多"Hello" * 3 # => "HelloHelloHello"# 一個字符串可以被看做字符串列表"This is a string"[0] # => 'T'# 可以獲取字符串的長度len("This is a string") # => 16# 使用 % 來對字符串進行格式化,但是在3.1后面的版本將會被棄用.x = 'apple'y = 'lemon'z = "The items in the basket are %s and %s" % (x, y)# 還有一種新的方法是使用format方法對字符串進行格式化,而且這也是首選的方法"{} is a {}".format("This", "placeholder")"{0} can be {1}".format("strings", "formatted")# You can use keywords if you don't want to count."{name} wants to eat {food}".format(name="Bob", food="lasagna")# None 是一個對象None # => None# 我們要使用"is"來比較一個對象是否為None,而不是"==" "etc" is None # => FalseNone is None # => True# 'is'可以測試對象的身份,但這個是對于對象來說有用,對于原始的值來說只能是然并卵# 任何一個對象都可以被用在一個布爾環(huán)境里面.# 下面這些值被認(rèn)為是錯誤的:# - None# - zero of any numeric type (e.g., 0, 0L, 0.0, 0j)# - empty sequences (e.g., '', (), [])# - empty containers (e.g., {}, set())# - instances of user-defined classes meeting certain conditions# see: https://docs.python.org/2/reference/datamodel.html#object.__nonzero__## 其它的值被認(rèn)為是正確的 (使用 bool() 函數(shù)返回的將是 True).bool(0) # => Falsebool("") # => False
# Python 又一個打印語句print "I'm Python. Nice to meet you!" # => I'm Python. Nice to meet you!# 從控制臺上獲得輸入數(shù)據(jù)的簡單方法input_string_var = raw_input("Enter some data: ") # 得到的是一個字符串input_var = input("Enter some data: ") # 將這個數(shù)據(jù)的值作為python代碼# 警告: 建議謹(jǐn)慎使用 input() 方法# 注意: 在 python 3, input() 被棄用,并且raw_input() 重命名為 input()# 在賦值變量前不需要聲明,這個不像C++那樣繁瑣.some_var = 5 # 慣例是使用小寫和下劃線some_var # => 5# 使用一個之前沒有賦值的變量是一種異常.# 看報錯內(nèi)容可以了解更多的異常信息.some_other_var # 報 name error# 使用一個表達式"yahoo!" if 3 > 2 else 2 # => "yahoo!"# 空列表li = []# 直接賦值列表other_li = [4, 5, 6]# 使用 append 方法為列表的末尾添加成員li.append(1) # li 現(xiàn)在是 [1]li.append(2) # li 現(xiàn)在是 [1, 2]li.append(4) # li 現(xiàn)在是 [1, 2, 4]li.append(3) # li 現(xiàn)在是 [1, 2, 4, 3]# 使用 pop 方法可以從列表的末尾刪除一個成員li.pop() # => 3 and li 現(xiàn)在是 [1, 2, 4]# Let's put it backli.append(3) # li 現(xiàn)在又是 [1, 2, 4, 3] .# 訪問列表就跟訪問數(shù)組一樣li[0] # => 1# 分配新值給索引指向的值li[0] = 42li[0] # => 42li[0] = 1 # 注意:把它設(shè)置成原來的值# 查看最后一個元素li[-1] # => 3# 如果查詢的是一個超出索引的值就會報錯li[4] # Raises an IndexError# 你可以使用切片語法獲取一個范圍內(nèi)的值.# (開始和結(jié)束取決于你的數(shù)字位置.)li[1:3] # => [2, 4]# 省略開始li[2:] # => [4, 3]# 省略結(jié)束li[:3] # => [1, 2, 4]# 每兩條選擇一個li[::2] # =>[1, 4]# 反轉(zhuǎn)整個列表li[::-1] # => [3, 4, 2, 1]# 把他們結(jié)合起來做一個更先進的切片# li[start:end:step]# 使用"del"刪除列表中的任意元素del li[2] # li is now [1, 2, 3]# 通過列表相加的方式得到一個新列表li + other_li # => [1, 2, 3, 4, 5, 6]# 注意: 原來的列表的值是沒有改變的.# 使用"extend()"方法對一個列表添加另一個列表li.extend(other_li) # 現(xiàn)在li變成了 [1, 2, 3, 4, 5, 6]# 刪除第一個出現(xiàn)的值li.remove(2) # li is now [1, 3, 4, 5, 6]li.remove(2) # Raises a ValueError as 2 is not in the list# 在指定的索引出插入一個值li.insert(1, 2) # li is now [1, 2, 3, 4, 5, 6] again# 找到這個值對應(yīng)的索引li.index(2) # => 1li.index(7) # Raises a ValueError as 7 is not in the list# 使用 "in" 檢查元素是否在列表中1 in li # => True# 使用 "len()" 查看列表的長度len(li) # => 6# 元組跟列表很像,但是不能改變.tup = (1, 2, 3)tup[0] # => 1tup[0] = 3 # Raises a TypeError# 對于列表的很多操作,在元組中同樣也可以len(tup) # => 3tup + (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 3d, e, f = 4, 5, 6 # you can leave out the parentheses# 如果沒有括號,將會默認(rèn)創(chuàng)建一個元組g = 4, 5, 6 # => (4, 5, 6)# 現(xiàn)在如果要交換兩個值將會變得非常簡單e, d = d, e # d is now 5 and e is now 4# 字典主要存儲映射empty_dict = {}# 直接賦值字典filled_dict = {"one": 1, "two": 2, "three": 3}# 使用 [] 查找字典里的值filled_dict["one"] # => 1# 使用 "keys()" 可以得到所有的鍵值filled_dict.keys() # => ["three", "two", "one"]# 注意- 字典的鍵是無須的,所以得到的值可能跟你一開始定義的不一樣# 使用 "values()" 可以得到所有的值filled_dict.values() # => [3, 2, 1]# 注意- 同樣的值是無須的.# 使用"items()"可以得到一個以列表中的元組形式的“鍵值-值”對filled_dict.items() # => [("one", 1), ("two", 2), ("three", 3)]# 使用 "in" 檢查元素鍵是否在字典中"one" in filled_dict # => True1 in filled_dict # => False# 查詢不存在的健是一個 KeyErrorfilled_dict["four"] # KeyError# 使用 "get()" 可以避免上面的錯誤,如果沒有就會返回Nonefilled_dict.get("one") # => 1filled_dict.get("four") # => None# 通過設(shè)置默認(rèn)值的方式,可以顯示沒有鍵情況下的值filled_dict.get("one", 4) # => 1filled_dict.get("four", 4) # => 4# 注意這時候的 filled_dict.get("four") 還是 => None# (get 方法并不能添加字典里面的值)# 設(shè)置健值的方法跟列表的類似,直接賦值filled_dict["four"] = 4 # now, filled_dict["four"] => 4# 使用 "setdefault()" 方法,當(dāng)鍵不存在的時候就設(shè)置這個鍵和值,但是如果存在就不進行改變filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5filled_dict.setdefault("five", 6) # filled_dict["five"] is still 5# 集合跟列表也很類似,但是不能包含重復(fù)值empty_set = set()# 使用 "set()" 對一群治進行初始化some_set = set([1, 2, 2, 3, 4]) # some_set is now set([1, 2, 3, 4])# 雖然它看起來是經(jīng)過排序的,但是實際上它是無序的another_set = set([4, 3, 2, 2, 1]) # another_set is now set([1, 2, 3, 4])# 從 2.7 開始, {} 可以用來聲明一個集合filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4}# 向集合中添加更多的成員filled_set.add(5) # filled_set is now {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}# 使用 - 可以得到補集{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}# 使用 ^ 得到交集的補集{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5}# 檢查左邊是否是右邊的超集{1, 2} >= {1, 2, 3} # => False# 檢查左邊是否是右邊的子集{1, 2} <= {1, 2, 3} # => True# 使用 in 檢查是否在集合中2 in filled_set # => True10 in filled_set # => False10 not in filled_set # => True# 查看變量的數(shù)據(jù)類型type(li) # => listtype(filled_dict) # => dicttype(5) # => int
# 先來一個變量some_var = 5# 這里又一個聲明,縮進在python里非常重要!# 打印"some_var is smaller than 10"if some_var > 10: print "some_var is totally bigger than 10."elif some_var < 10: # 這個 else 字句是可有可無的,根據(jù)需要. print "some_var is smaller than 10."else: # 這個也是. print "some_var is indeed 10.""""For 循環(huán)在列表中遍歷prints: dog is a mammal cat is a mammal mouse is a mammal"""for animal in ["dog", "cat", "mouse"]: # 你可以使用 {0} 得到format里面的字符串. (See above.) print "{0} is a mammal".format(animal)""""range(number)" 返回一個數(shù)字列表from 0 to 給出去的數(shù)字prints: 0 1 2 3"""for i in range(4): print i""""range(lower, upper)" 返回一個數(shù)字列表from 小的數(shù)字 to 大的數(shù)字prints: 4 5 6 7"""for i in range(4, 8): print i"""While 循環(huán)遇到條件就不在運行.prints: 0 1 2 3"""x = 0while x < 4: print x x += 1 # 縮寫 x = x + 1# 處理異常使用 try/except 模塊try: # 使用 "raise" 來提示錯誤內(nèi)容 raise IndexError("This is an index error")except IndexError as e: pass # Pass 就是一個空操作,但是你要寫在這里.except (TypeError, NameError): pass # 如果需要,可以將多個異常處理掉.else: # 可用可不用,根據(jù)需求,但是要在所有的except后面而且要符合邏輯 print "All good!" # 只會在沒有報錯的時候運行finally: # 在所有情況下都會執(zhí)行 print "We can clean up resources here"# 你可以使用下面這個字句代替 try/finally with open("myfile.txt") as f: for line in f: print line
# 使用 "def" 來創(chuàng)建一個函數(shù)def add(x, y): print "x is {0} and y is {1}".format(x, y) return x + y # 使用 return 字句返回值# 使員工參數(shù)調(diào)用函數(shù)add(5, 6) # => 打印 "x is 5 and y is 6" 并且返回值 11# 還可以使用關(guān)鍵字參數(shù)調(diào)用函數(shù)add(y=6, x=5) # 關(guān)鍵字參數(shù)不需要在意排序.# 你可以使用 * 定義函數(shù)的位置變量參數(shù),使用的時候會被當(dāng)做一個元組def varargs(*args): return argsvarargs(1, 2, 3) # => (1, 2, 3)# 你還可以使用 ** 定義函數(shù)的關(guān)鍵字變量參數(shù),使用的時候會被當(dāng)做一個字典def keyword_args(**kwargs): return kwargs# 調(diào)用之后看看會發(fā)生什么keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}# 只要你想要,兩個一起上也可以def all_the_args(*args, **kwargs): print args print kwargs"""all_the_args(1, 2, a=3, b=4) prints: (1, 2) {"a": 3, "b": 4}"""# 調(diào)用函數(shù)的時候,你也可以對 args/kwargs 做相反的操作!# 先定義相關(guān)的args/kwargs,然后使用 * 傳遞位置參數(shù)、使員工 **傳遞關(guān)鍵字參數(shù).args = (1, 2, 3, 4)kwargs = {"a": 3, "b": 4}all_the_args(*args) # 相當(dāng)于 all_the_args(1, 2, 3, 4)all_the_args(**kwargs) # 相當(dāng)于 all_the_args(a=3, b=4)all_the_args(*args, **kwargs) # 相當(dāng)于 all_the_args(1, 2, 3, 4, a=3, b=4)# 還可以分別使用 * and ** 來接受并傳遞其他函數(shù)的參數(shù)def pass_all_the_args(*args, **kwargs): all_the_args(*args, **kwargs) print varargs(*args) print keyword_args(**kwargs)# 函數(shù)范圍x = 5def set_x(num): # 局部變量 x 跟全局變量 x 不一樣 x = num # => 43 print x # => 43def set_global_x(num): global x print x # => 5 x = num # 全局變量 x 現(xiàn)在變成了 6 print x # => 6set_x(43)set_global_x(6)# Python 有第一類型"""備注:根據(jù)變量的取值范圍、可操作性、可賦值性可以三種類型:一級:可以作為參數(shù)傳遞也可以作為結(jié)果返回;二級:可以作為參數(shù)傳遞,但是不能作為結(jié)果返回,也不能復(fù)制給變量;三級:連作為參數(shù)傳遞也不行。"""def create_adder(x): def adder(y): return x + y return adderadd_10 = create_adder(10)add_10(3) # => 13# 還有一些匿名函數(shù)(lambda x: x > 2)(3) # => True(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5# 還有內(nèi)置的一些高階函數(shù)map(add_10, [1, 2, 3]) # => [11, 12, 13],map根據(jù)給定的函數(shù)對指定序列做映射map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3],提供兩個列表,對相同的位置進行maxfilter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]# 我們可以使用列表來更好的理解 maps 和 filters 函數(shù)[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13][x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7]# 你也可以構(gòu)造字典或集合去理解.{x for x in 'abcddeef' if x in 'abc'} # => {'a', 'b', 'c'}{x: x ** 2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# 我們從對象的子類中得到一個類.class Human(object): # 類的屬性. 它會被這個類的所有實例共享 species = "H. sapiens" # 當(dāng)類被實例化時,稱為基本的初始化. # 注意雙前下劃線和雙后下劃線表示python所使用的對象和或?qū)傩?,它們存在于用戶空盒子的名稱空間中,這些名字你最好別自己命名 def __init__(self, name): # 分配參數(shù)給這個實例的 name 屬性 self.name = name # 初始化屬性 self.age = 0 # 一個實例的方法. 所有的方法使用 "self" 作為第一個參數(shù) def say(self, msg): return "{0}: {1}".format(self.name, msg) # 一個類方法是所有實例之間共享的 # 它們作為第一參數(shù),稱為調(diào)用類 @classmethod def get_species(cls): return cls.species # 在沒有類和實例的情況下調(diào)用靜態(tài)方法 @staticmethod def grunt(): return "*grunt*" """ 絲毫沒有g(shù)et到最后這三種方法的用處 """ # property 方法就像 getter 方法. # 它將類方法轉(zhuǎn)化為一個相同名稱的只讀屬性. @property def age(self): return self._age # 允許去設(shè)置屬性 @age.setter def age(self, age): self._age = age # 允許刪除屬性 @age.deleter def age(self): del self._age# 初始化類i = Human(name="Ian")print i.say("hi") # prints out "Ian: hi"j = Human("Joel")print j.say("hello") # prints out "Joel: hello"# 調(diào)用類方法i.get_species() # => "H. sapiens"# 改變共有屬性Human.species = "H. neanderthalensis"i.get_species() # => "H. neanderthalensis"j.get_species() # => "H. neanderthalensis"# 調(diào)用靜態(tài)方法Human.grunt() # => "*grunt*"# 更新屬性i.age = 42# 得到屬性i.age # => 42# 刪除屬性del i.agei.age # => raises an AttributeError##################################################### 6. 模塊##################################################### 引入模塊import mathprint math.sqrt(16) # => 4# 從模塊中引入指定函數(shù)from math import ceil, floorprint ceil(3.7) # => 4.0print floor(3.7) # => 3.0# 從模塊中引入所有的函數(shù).# Warning: 不推薦這么做from math import *# 還可以對模塊重命名import math as mmath.sqrt(16) == m.sqrt(16) # => True# y你可以測試下這些其實等價的from math import sqrtmath.sqrt == m.sqrt == sqrt # => True# Python的模塊值是普通的文件.你可以自己寫個,然后引入. 模塊的名稱就是文件的名稱.# 你可以找出是哪些函數(shù)和屬性定義了一個模塊import mathdir(math)# 如果在現(xiàn)有模塊的文件夾中有一個腳本名稱為 math.py ,這個腳本將會代替Python的自建模塊,這是因為本地的文件優(yōu)先級高于自建的庫
# 生成器# A generator "generates" values as they are requested instead of storing everything up front# The following method (*NOT* a generator) will double all values and store it in `double_arr`. For large size of iterables, that might get huge!def double_numbers(iterable): double_arr = [] for i in iterable: double_arr.append(i + i) return double_arr# Running the following would mean we'll double all values first and return all of them back to be checked by our conditionfor value in double_numbers(range(1000000)): # `test_non_generator` print value if value > 5: break# We could instead use a generator to "generate" the doubled value as the item is being requesteddef double_numbers_generator(iterable): for i in iterable: yield i + i# Running the same code as before, but with a generator, now allows us to iterate over the values and doubling them one by one as they are being consumed by our logic. Hence as soon as we see a value > 5, we break out of the loop and don't need to double most of the values sent in (MUCH FASTER!)for value in double_numbers_generator(xrange(1000000)): # `test_generator` print value if value > 5: break# BTW: did you notice the use of `range` in `test_non_generator` and `xrange` in `test_generator`?# Just as `double_numbers_generator` is the generator version of `double_numbers`# We have `xrange` as the generator version of `range`# `range` would return back and array with 1000000 values for us to use# `xrange` would generate 1000000 values for us as we request / iterate over those items# Just as you can create a list comprehension, you can create generator comprehensions as well.values = (-x for x in [1, 2, 3, 4, 5])for x in values: print(x) # prints -1 -2 -3 -4 -5 to console/terminal# You can also cast a generator comprehension directly to a list.values = (-x for x in [1, 2, 3, 4, 5])gen_to_list = list(values)print(gen_to_list) # => [-1, -2, -3, -4, -5]# 裝飾器# A decorator is a higher order function, which accepts and returns a function.# Simple usage example – add_apples decorator will add 'Apple' element into fruits list returned by get_fruits target function.def add_apples(func): def get_fruits(): fruits = func() fruits.append('Apple') return fruits return get_fruits@add_applesdef get_fruits(): return ['Banana', 'Mango', 'Orange']# Prints out the list of fruits with 'Apple' element in it: Banana, Mango, Orange, Appleprint ', '.join(get_fruits())# in this example beg wraps say# Beg will call say. If say_please is True then it will change the returned messagefrom functools import wrapsdef beg(target_function): @wraps(target_function) def wrapper(*args, **kwargs): msg, say_please = target_function(*args, **kwargs) if say_please: return "{} {}".format(msg, "Please! I am poor :(") return msg return wrapper@begdef say(say_please=False): msg = "Can you buy me a beer?" return msg, say_pleaseprint say() # Can you buy me a beer?print say(say_please=True) # Can you buy me a beer? Please! I am poor :(