python那些套路你知道嗎?十分鐘給你科普一下!(附python教程)


python那些套路你知道嗎?十分鐘給你科普一下!(附python教程)


本文面向對象為具有一丁點編程經驗的小夥伴,旨在快速瞭解Python的基本語法和部分特性。前言# Python中單行註釋請用‘#’""" Python中多行註釋請用""",我寫不了那麼多字,隨便湊個樣板。"""1. 基本類型和運算符# 定義了一個數字 33 # => 3# 基本計算1 + 1 # => 28 - 1 # => 710 * 2 # => 2035 / 5 # => 7# 當除數和被除數都為整型時,除 這個操作只求整數 # ( python2.x語法。經測試,Python3.x 已經全部當做浮點數處理,還會計算小數)5 / 2 # => 210/-3 #python3的結果為-3.3333333333333335 python2 結果為-410/3 #python3的結果為3.3333333333333335 python2 結果為3 #由上面兩個結果也可以看出,在Python2中,如結果有小數,則會取最近最小整數# 如果我們除數和被除數為浮點型,則Python會自動把結果保存為浮點數2.0 # 這是浮點數11.0 / 4.0 # 這個時候結果就是2.75啦!是不是很神奇? # 當用‘//’進行計算時,python3不會全部單做浮點數處理.5 // 3 # => 15.0 // 3.0 # => 1.0 -5 // 3 # => -2-5.0 // 3.0 # => -2.0from __future__ import division # 注可以在通過 __future__ 關鍵字# 在python2中引入python3 特性11/4 # => 2.75 ... 標準除法11//4 # => 2 ... 除後取整# 求餘數操作7 % 3 # => 1# 冪操作 2的4次方2**4 # => 16# 先乘除,後加減,口號優先(1 + 3) * 2 # => 8# 布爾值操作# 注:or 和 and 兩個關鍵字是大小寫敏感的True and False #=> 返回FalseFalse or True #=> 返回True# 布爾值和整形的關係,除了0外,其他都為真0 and 2 #=> 0-5 or 0 #=> -50 == False #=> True2 == True #=> False1 == True #=> True# not 操作not True # => Falsenot False # => True#等值比較 “==”,相等返回值為True ,不相等返回False1 == 1 # => True2 == 1 # => False# 非等比較“!=”,如果兩個數不相等返回True,相等返回Flase1 != 1 # => False2 != 1 # => True# 大於/小於 和等於的組合比較1 < 10 # => True1 > 10 # => False2 <= 2 # => True2 >= 2 # => True# Python可以支持多數值進行組合比較,#但只要一個等值為False,則結果為False1 < 2 < 3 # => True2 < 3 < 2 # => False# 可以通過 " 或者 '來創建字符串"This is a string."'This is also a string.'# 字符串間可以通過 + 號進行相加,是不是簡單到爆?"Hello " + "world!" # => "Hello world!"# 甚至不使用'+'號,也可以把字符串進行連接"Hello " "world!" # => "Hello world!"#可以通過 * 號,對字符串進行復制,比如 ;importantNote = "重要的事情說三遍\\n" * 3 print (importantNote)""" 結果為:重要的事情說三遍重要的事情說三遍重要的事情說三遍""""Hello" * 3 # => "HelloHelloHello"# 字符串可以在任意位置被打斷"This is a string"[0] # => 'T'#字符串可以用 %連接,並且可以打印出變量值#(和C/C++ 一樣%d 表示整數,%s表示字符串,#但python可以自己進行判斷,我們無需太擔心這個問題)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,它是一個特殊的變量None # => None# 在和None進行比較時,不要用“==”操作符,用 “is”"etc" is None # => FalseNone is None # => True#“is"操作符用於對象之間的比較,#對於底層類型進行比較時#不建議用“is”,但對於對象之間的比較,用“is”是最合適的# bool可以用於對任何對象進行判斷# 以下這些值是非真的# - None# - 各類數值型的0 (e.g., 0, 0L, 0.0, 0j)# - 空元組、空列表 (e.g., '', (), [])# - 空字典、空集合 (e.g., {}, set())# - 其他值請參考:# https://docs.python.org/2/reference/datamodel.html#object.__nonzero__## All other values are truthy (using the bool() function on them returns True).bool(0) # => Falsebool("") # => False2. 變量和集合# 打印 print()print ("I'm Python. Nice to meet you!") # => I'm Python. Nice to meet you!# 從控制檯中獲取輸入input_string_var = raw_input("Enter some data: ") # 返回字符串類型input_var = input("Enter some data: ") # python會判斷類型如果是字符串 則輸入時要加“”or''# 注意:在 python 3中, input() 由 raw_input() 代替# 在Python中不需要設定變量類型,python會自動根據值進行判斷some_var = 5 some_var # => 5# if 可以作為表達時被使用,下句可以這樣理解 “輸出‘yahool’如果3大於2的話,不然輸出2“"yahoo!" if 3 > 2 else 2 # => "yahoo!"

列表

# python中的列表定義li = []# 也可以通過初始化時內置列表的值other_li = [4, 5, 6]# append函數可以在列表中插入值li.append(1) # li is now [1]li.append(2) # li is now [1, 2]li.append(4) # li is now [1, 2, 4]li.append(3) # li is now [1, 2, 4, 3]# pop函數從列表末移除值li.pop() # => 3 and li is now [1, 2, 4]# 移除後通過append接回li.append(3) # li is now [1, 2, 4, 3] again.# 通過[]的方式可以提取任何列表中的任意值#(前提,index不大於列表總數)li[0] # => 1# 也可以通過[]下標的方式直接給列表賦值li[0] = 42li[0] # => 42# 如果[]小標的值為負數,則表示以逆序獲取列表中的值li[-1] # => 3# 查詢的值不可以超出列表個數,否則報錯。# 但是利用insert()插入時可以,超出範圍的值會直接被插入到列表最末li[4] # Raises an IndexError# 可以通過[:],獲取列表中指定範圍的值# (It's a closed/open range for you mathy types.)# 這是半開取值法,比如li[1:3],取的是列表中index為1、2的兩個值,# 該法則適用於以下所有通過[]取值的方式li[1:3] # => [2, 4]# 如果一邊不去值,則表示取所有該邊的值。li[2:] # => [4, 3]li[:3] # => [1, 2, 4]# [::2]表示選擇從[0]開始,步長為2上的值li[::2] # =>[1, 4]# [::-1]表示反向選擇,-可以理解為 反向選擇,而1表示步長,步長1則包含了列表中的所有元素li[::-1] # => [3, 4, 2, 1]# []規則完整版表示方法[開始:結束:步長]# li[start:end:step]# "del"關鍵字可以直接刪除列表中的值del li[2] # li is now [1, 2, 3]# 可以通過“+”操作符對列表進行操作,注:列表只有 + 操作,而集合(set)有+ 和 -li + other_li # => [1, 2, 3, 4, 5, 6]# 也可以 "extend()"方法對列表進行擴展li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6]# Remove 方法和 del 類似,但remove的直接是數值,而不是indexli.remove(2) # li is now [1, 3, 4, 5, 6]li.remove(2) # 如果remove的值不存在列表中,則會報錯# 在指定位置插入數值,上面已經提過,如果index值超過的話,會直接插到列表末li.insert(1, 2) # li is now [1, 2, 3, 4, 5, 6] again# 獲取某個值的indexli.index(2) # => 1li.index(7) # 如果# "in"可以直接查看某個值是否存在於列表中1 in li # => True# "len()"函數可以檢測隊列的數量len(li) # => 6

python那些套路你知道嗎?十分鐘給你科普一下!(附python教程)


元組

# Tuples(元組)是一個類似數列的數據結構,但是元組是不可修改的tup = (1, 2, 3)tup[0] # => 1tup[0] = 3 # 一修改就會報錯#數列中的方法在元組也可以使用(除了 修改)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 為1,b為2,c為3d, e, f = 4, 5, 6 # 元組賦值也可以不用括號# 同樣元組不用括號也同樣可以創建g = 4, 5, 6 # => (4, 5, 6)# Python中的數據交換十分簡單:只要在賦值時互調位置即可e, d = d, e # d is now 5 and e is now 4

字典

# Python中的字典定義empty_dict = {}# 也可以通過定義時賦值給字典filled_dict = {"one": 1, "two": 2, "three": 3}# 可以通過[]的key方式查詢字典中的值filled_dict["one"] # => 1# 可以通過"keys()"方法獲取字典中的所有key值filled_dict.keys() # => ["three", "two", "one"]# Note - 返回的keys並不一定按照順序排列的.# 所以測試結果可能和上述結果不一致# 通過 "values()"的方式可以獲取字典中所有值,#同樣他們返回的結果也不一定按照順序排列filled_dict.values() # => [3, 2, 1]# 可以通過 "in"方式獲取查詢某個鍵值是否存在字典中,但是數值不可以"one" in filled_dict # => True1 in filled_dict # => False# 查找不存在的key值時,Python會報錯filled_dict["four"] # KeyError#用 "get()" 方法可以避免鍵值錯誤的產生filled_dict.get("one") # => 1filled_dict.get("four") # => None# 當鍵值不存在的時候,get方法可以通過返回默認值,# 但是並沒有對值字典進行賦值filled_dict.get("one", 4) # => 1filled_dict.get("four", 4) # => 4# 字典中設置值的方式和列表類似,通過[]方式可以設置filled_dict["four"] = 4 # now, filled_dict["four"] => 4# "setdefault()" 可以設置字典中的值# 但是注意:只有當該鍵值之前未存在的時候,setdefault()函數才生效filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5filled_dict.setdefault("five", 6) # filled_dict["five"] is still 5

集合

empty_set = set()# 初始化set的方式可以通過 set()來實現some_set = set([1, 2, 2, 3, 4]) # some_set is now set([1, 2, 3, 4])# 集合的排列是無序的!集合的排列是無序的!集合的排列是無序的!another_set = set([4, 3, 2, 2, 1]) # another_set is now set([1, 2, 3, 4])# Python2.7以後,{}可以用於被定義集合filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4}# Add方法可用於增加集合成員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 # => False

Python數據集合類型總結

  • 列表 定義方式 li = [1,2,3,4,“Hello World”] (列表可以包含任意基本類型)
  • 元組 定義方式 tup = (1,2,3,4) (和列表類似,但 元組不可更改
  • 字典 定義方式 dic = {“one”:2,“tow”:3,“three”:0}(字典,就是字典嘛。以 key:value 方式存在)
  • 集合 定義方式 set=set(1,2,3,4)or set = {1,2,3,4} (集合裡的元素是唯一的,集合支持 & | ^ + -操作)

3. Python 邏輯運算符# 創建一個變量some_var = 5# 通過if進行邏輯判斷if some_var > 10:print "some_var is totally bigger than 10."elif some_var < 10: # This elif clause is optional.print "some_var is smaller than 10."else: # This is optional too.print "some_var is indeed 10.""""通過for...in...進行循環打印:dog is a mammalcat is a mammalmouse is a mammal"""for animal in ["dog", "cat", "mouse"]:# You can use {0} to interpolate formatted strings. (See above.)print "{0} is a mammal".format(animal)"""通過"range()" 方式,控制for的循環次數prints:0123"""for i in range(4):print i""""range(lower, upper)" 返回 lower 到 upper的值,注意:range左邊必須小於右邊參數prints:4567"""for i in range(4, 8):print i"""while 循環prints:0123"""x = 0while x < 4:print xx += 1 # Shorthand for x = x + 1# Python支持 try/except 語法# Python2.6以上的版本,支持try...except...:try:# raise顯示地引發異常。一旦執行了raise語句,raise後面的語句將不能執行。raise IndexError("This is an index error")except IndexError as e:pass # pass 空語句,跳過處理except (TypeError, NameError):pass # python 支持同時檢測多個錯誤else: # Python必須要處理所有情況,這裡是其他未定義的情況print "All good!" finally: # finally無論有沒有異常都會執行print "We can clean up resources here"#通過with函數,可以替代try....except...函數 [with詳解](http://www.ibm.com/developerworks/cn/opensource/os-cn-pythonwith/)with open("myfile.txt") as f:for line in f:print line4. Functions# def 關鍵字定義函數def add(x, y):print "x is {0} and y is {1}".format(x, y)return x + y #可以直接return結果# 函數調用參數add(5, 6) # => prints out "x is 5 and y is 6" and returns 11# Python支持參數互換,只需要在調用函數時加上形參add(y=6, x=5) # Keyword arguments can arrive in any order.# Python函數支持可變參數# 在定義函數時通過*號表示可變長參數def varargs(*args):return argsvarargs(1, 2, 3) # => (1, 2, 3)# 可以通過**的方式定義Key可變長參數查找字典中的關鍵詞def keyword_args(**kwargs):return kwargs# 當函數參數是**類型的時候,Python可以通過該函數定義字典keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}#同時支持函數和字典類型參數,具體事例如下:def all_the_args(*args, **kwargs):print argsprint kwargs"""all_the_args(1, 2, a=3, b=4) prints:(1, 2){"a": 3, "b": 4}"""# 在調用函數時,可以同時賦值,文字難以表達,例子如下:args = (1, 2, 3, 4)kwargs = {"a": 3, "b": 4}all_the_args(*args) # equivalent to foo(1, 2, 3, 4)all_the_args(**kwargs) # equivalent to foo(a=3, b=4)all_the_args(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4)# 在函數中也可以通過單獨處理* 或者 **的方式,增加函數的健壯性def pass_all_the_args(*args, **kwargs):all_the_args(*args, **kwargs)print varargs(*args)print keyword_args(**kwargs)# 全局變量 Xx = 5def set_x(num):# 當在函數里面改變變量時,如果沒有加gloabl關鍵字,則改變的是局部變量x = num # => 43print x # => 43def set_global_x(num):global xprint x # => 5x = num # 加了global關鍵字後,即可在函數內操作全局變量print x # => 6set_x(43)set_global_x(6)# 返回函數指針方式定義函數/*換個說法,匿名函數*/def create_adder(x):def adder(y):return x + yreturn adderadd_10 = create_adder(10)add_10(3) # => 13# Lambda 關鍵字定義的匿名函數(lambda x: x > 2)(3) # => True (lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5# map方式也可以調用函數並傳入參數map(add_10, [1, 2, 3]) # => [11, 12, 13]map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3]filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]# 可以通過這兩種方式結合調用,下面的函數解析:#add_10(i) 是映射了for...in...函數的返回值,返回值作為參數傳進。[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]5. Python中的類# 下面代碼是定義了一個Human類,繼承自object類# Python類可以繼承自多個類,如class Human(object,orangOutang)class Human(object):# 類變量species = "H. sapiens"類接口__species = "Other.sapiens" #內部結構,無法被外部直接訪問# __init__(),初始化函數,python中在對類進行處理時,會先處理以下函數,#其實就是系統默認定義了接口,而這個接口是開放給用戶去實現的,具體如下: #__init__ 構造函數,在生成對象時調用# __del__ 析構函數,釋放對象時使用#__repr__ 打印,轉換#__setitem__按照索引賦值#__getitem__按照索引獲取值#__len__獲得長度#__cmp__比較運算#__call__函數調用#__add__加運算#__sub__減運算#__mul__乘運算#__div__除運算#__mod__求餘運算#__pow__稱方def __init__(self, name):#聲明類中的屬性,並初始化,在初始化的時候同時#就是定義了變量類型self.name = nameself.age = 0# 在類中所有函數都必須把self作為第一個參數#(下面定義的類方法和靜態方法除外)def say(self, msg):return "{0}: {1}".format(self.name, msg)# 類方法@classmethoddef get_species(cls):return cls.species# 靜態方法,@staticmethoddef grunt():return "*grunt*"# A property is just like a getter.# It turns the method age() into an read-only attribute# of the same name.#property屬性,相當於getter@propertydef age(self):return self._age# This allows the property to be [email protected] age(self, age):self._age = age# This allows the property to be [email protected] 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"#調用實例方法用"."i.get_species() # => "H. sapiens"# 改變類變量Human.species = "H. neanderthalensis"i.get_species() # => "H. neanderthalensis"j.get_species() # => "H. neanderthalensis"# 調用靜態方法Human.grunt() # => "*grunt*"# 給age賦值i.age = 42# 獲取age值i.age # => 42# 刪除agedel i.agei.age # => raises an AttributeError6. Python的模塊(庫)# Python中的一個*.py文件就是一個模塊import mathprint math.sqrt(16) # => 4# 可以只引入模塊中的某些類/方法from math import ceil, floorprint ceil(3.7) # => 4.0print floor(3.7) # => 3.0# 也可以通過*引入全部方法# Warning: this is not recommendedfrom math import *#math庫的縮寫可以為mmath.sqrt(16) == m.sqrt(16) # => True# 可以直接引入sqrt庫from math import sqrtmath.sqrt == m.sqrt == sqrt # => True#python的庫就只是文件import mathdir(math)# If you have a Python>

最後為大家準備了一些python的學習教程分享,希望可以幫助到大家。

python那些套路你知道嗎?十分鐘給你科普一下!(附python教程)


獲取方式:請大家轉發+關注並私信小編關鍵詞:“資料”即可獲取!


分享到:


相關文章: