Python學習(一)基礎知識


參考資料:https://github.com/lijin-THU/notes-python(相應實體書為:《自學Python——編程基礎、科學計算及數據分析》)

 

1. Python之禪:import this

 Python的標准庫提供了一個 keyword 模塊,可以輸出當前版本的所有關鍵字:import keyword + keyword.kwlist

2. iPython使用

  • %lsmagic  //查看所有magic命令;line magic % 作用於一行,cell magic %% 作用於整個cell
  • %pylab  //導入numpy和matplotlib兩個包
  • %matplotlib inline  //頁面內嵌畫圖,非彈窗 + import matplotlib + import matplotlib.pyplot as plt
  • ?  //使用 ? 查看函數的幫助,如sum?
  • ??  //使用 ?? 查看函數幫助和函數源代碼,sum??
  • !ping baidu.com  //使用 ! 來執行一些系統命令
  • _  // _ 上個cell的輸出結果
  • %run、%timeit、%%writefile、%precision

3. Python支持鏈式比較:x = 2; 1 < x <= 3  輸出True

4. list.append():每次只添加一個元素,並不會因為這個元素是序列而將其展開(不展開

5. list.extend(lst):將序列lst的元素依次添加到列表list的最后,相當於list += lst

6. 數據類型

  • 不可變類型:基本類型(整型、長整型、浮點數等)+ 復數 + 元組 + 字符串 +不可變集合(frozen set)
  • 可變類型:列表 + 字典 + 集合 + numpy數組 + 用戶自定義類型;

7. 賦值機制(02.13 how-python-assignment-works

(1)對於簡單類型而言,python會為每個出現的對象進行賦值(分配內存),哪怕它們的值是一樣的;不過,為了提高內存利用效率,對於一些簡單的對象,如一些數值較小的int對象,python采用了重用對象內存的辦法;  //可以使用 id() 函數查看內存地址,如id(x)返回變量x的內存地址;或者使用 is 來判斷是不是指向同一個事物(內存地址),如 x is y 返回True或False

(2)對於容器類型而言,python給新對象賦值時,僅僅是指向同一塊內存空間(不分配新內存),如 x = [500, 501, 502]; y = x;  //改變列表數據時,會分配新的內存空間給新值,而舊值則會python自動調用垃圾處理機制回收

8. 生成隨機數函數:range(), xrange()  //xrange效果與range函數相同,但是xrange並不會一次性的產生所有的數據,可以節省時間和內存消耗

  • %timeit for i in xrange(1000000): i = i  //運行時間較快
  • %timeit for i in range(1000000): i = i  //運行時間較慢,一次性產生所有數據

9. 列表推導式 x = range(1000000)

  • %timeit total = sum([i**2 for i in x])  //運行時間較慢,python會一次性生成整個臨時列表,再進行求和,臨時列表會被垃圾回收機制回收
  • %timeit total = sum(i**2 for i in x)  //運行時間較快,類似上述xrange()

10. map方法生成序列:map(aFun, aSeq)  //將函數 aFun 應用到序列 aSeq 上的每一個元素上,返回一個列表,不管這個序列原來是什么類型

1 def sqr(x): 
2     return x ** 2
3 
4 a = [2, 3, 4]
5 print map(sqr, a)
輸出:[4 9 6]

注:根據函數參數的多少,map 可以接受多組序列,將其對應的元素作為參數傳入函數

1 def add(x, y): 
2     return x + y
3 
4 a = (2, 3, 4)
5 b = [10, 5, 3]
6 print map(add, a, b)
輸出:[12 8 7]

11. 函數通過元組和字典傳入參數  //結合可變參數的函數定義方式進行思考def func(arg1, *arg2, **arg3):  位置參數在前,鍵值對參數在后

1 def add(x, y):
2     """Add two numbers"""
3     a = x + y
4     return a
5     
6 z = (2, 3)
7 print add(*z)  #傳入元組參數z,其中 * 必不可少
輸出:5
1 def add(x, y):
2     """Add two numbers"""
3     a = x + y
4     return a
5 
6 w = {'x': 2, 'y': 3}
7 print add(**w)  #傳入字典參數w,其中 ** 必不可少
輸出:5

12. 模塊

  • import:載入模塊,在導入時,python會執行一遍模塊中的所有內容,包括輸出語句print

  注:為了提高效率,python只會載入模塊一次,已經載入的模塊再次載入時,Python並不會真正執行載入操作,哪怕模塊的內容已經改變

  • reload()函數:強制重新載入模塊 reload(module);Python 3把 reload 內置函數移到了 imp 標准庫模塊中,必須先導入 from imp import reload
 #利用__name__屬性,使得.py文件既能當作腳本,又能當作模塊用
1
PI = 3.1416 2 3 def sum(lst): 4 """ Sum the values in a list 5 """ 6 tot = 0 7 for value in lst: 8 tot = tot + value 9 return tot 10 11 def add(x, y): 12 " Add two values." 13 a = x + y 14 return a 15 16 def test(): 17 w = [0,1,2,3] 18 assert(sum(w) == 6) 19 print 'test passed.' 20 21 if __name__ == '__main__':  #當文件被當作腳本執行時,__name__的值為"__main__",會執行test()函數,當做模塊導入是,test()不執行 22 test()

13. 常用的標准庫

  • re 正則表達式
  • copy 復制
  • math, cmath 數學
  • decimal, fraction
  • sqlite3 數據庫
  • os, os.path 文件系統
  • gzip, bz2, zipfile, tarfile 壓縮文件
  • csv, netrc 各種文件格式
  • xml
  • htmllib
  • ftplib, socket
  • cmd 命令行
  • pdb
  • profile, cProfile, timeit
  • collections, heapq, bisect 數據結構
  • mmap
  • threading, Queue 並行
  • multiprocessing
  • subprocess
  • pickle, cPickle
  • struct

14. 警告warnings:出現了一些需要讓用戶知道的問題,但又不想停止程序,可以使用警告

1 import warnings
2 
3 def month_warning(m):
4     if not 1<= m <= 12:
5         msg = "month (%d) is not between 1 and 12" % m
6         warnings.warn(msg, RuntimeWarning)  #警告函數 7 
8 month_warning(13)
輸出:RuntimeWarning: month (13) is not between 1 and 12
#設置忽略特定類型的警告
1
warnings.filterwarnings(action = 'ignore', category = RuntimeWarning) 2 3 month_warning(13)  #沒有警告出現


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM