Python101
- 單雙引號不分
- 命名區分大小寫
- BIF buildInFunction 內置函數 dir()
- 註釋 “”“explain here”“”
- import sys; sys.path 查看py模塊
- python3 idle窗口運行
- python 主命名空間 main
- ()數據爲元組,tupe,不可變數據,[]爲可變數據
- 縮進來寫代碼塊,必須嚴格執行
- 數組讀取 a[0:3]
列表
列表CRUD
- 高層集合 可以混合各種數據
- 列表類似於數組,不需要刻意聲明數據類型
創建列表
cast = ["a",'b','c']
print(len(cast))
cast[1]
.append('a')
末尾加一
.extend('a','b')
末尾加多
.pop()
提取末尾
.remove('a')
刪指定
.insert(0,'a')
插入指定index,後續index值向後移
迭代 for…in…
for item in items:
print(item)
while … :
等同於上迭代
count=0
while count < len(cast):
print(cast[count])
count = count+1
列表嵌套
- 列表內可以隨意嵌套
創建3層迭代
movie = ['a',1,'b',2,'c',3,['a1','a2',['b1','b2']]]
print(movie[6][2][1]) //b2
- 用
for-in
會只迭代第一層
for item in movie: print (item)
//
a
...
3
['a1', 'a2', ['b1', 'b2']]
- 迭代3層,用
if:...else:
和isinstance(a,list)
檢測是否含有子列表。
isinstance(item,list)
檢測類型,內置BIF,list爲類型
for item in movie: //檢測第一層
if isinstance(item,list): //第二層
for item_0 in item:
if isinstance(item_0,list): //第三層
for item_1 in item_0:
print (item_1)
else:
print(item_0)
else: print (item)
def
創建函數
如果檢測到item爲list,則調用這身函數
def loop(the_list):
for item in the_list:
if isinstance(item,list):
loop(item)
else:
print(item)
print_loop 接受列表,以及通過空格顯示列表層數,默認設置爲false
def print_loop(the_list, indent=false, level=0)
for item in the_list:
if isinstance(item, list):
print_loop(item, indent, level+1)
else:
if indent:
for tab in range(level):
print("\t", end="") //end="" 後面加個空格
print(item)
運行py代碼,py模塊的創建和導入
把函數寫在.py的文件中,爲模塊。
在idle中兩種導入方式:
- 通過現成路徑中導入
import sys; sys.path
查看目前路徑,並在在路徑中添加hello.py
import hello
導入
hello.loop(movie)
使用函數,
引入模塊
以hello.loop(...)
引用函數
或者import loop from hello
引入到當前命名空間
- 打包發佈 distribution
創建hello文件夾,添加 hello.py
, setup.py
在hello文件下,終端運行:
python3 setup.py sdist
構建發佈文件
sudo python3 setup.py install
將發佈安裝到python本地副本中
import hello
導入
安裝後目錄結構 p69
hello
|
|__manifest //包含文件列表
|
|__build
| |__llb
| |__hello.py //代碼
|__dist
| |__apple-1.0.0.tar.gz //發佈包
|
|__apple.py //代碼
|
|__apple.pyc //‘編譯’版本的代碼
|
|__setup.py //元數據
上傳到PyPl
數據讀寫
python讀取機制
讀取txt文件 打印
import os
os.getcwd() //當前目錄
os.chdir('../a/b') //切換目錄
data = open('sketch.txt') //打開
print(data.readline(), end="") //打印單行
data.seek(0) //指針會到起點
for item in data: print(data, end="") //打印每一行
data.close() //關閉
分解數據 find split
find(:)==-1
查找
(role,words) = item.split(":",1)
split分開,兩部分
role = []
words = []
try:
data = open('sketch.txt')
for each_line in data:
try:
//if not each_line find(':') == -1:
(role, words) = each_line.split(":",1) //返回不可變數據
print(role)
print('said:said',end="")
print(words)
except ValueError
pass
data.close()
except IOError:
print('data has been missing')
...
寫入模式,訪問模式
open("date.out",w)
, 寫,清空文件,或者新建。
..., w+
打開文件讀寫,或者新建。
把保存放在finally:
,確保一定會保存,否則try中出現錯誤,數據丟失。
print(role, file=man_file)
把數據寫入
- 使用
try/except/finally
模式
...
try:
man_file = open('man_data.txt',w) //w讀取模式,新建文件
other_file = open('other_data.txt',w)
print(role, file = man_file) //用print寫入數據
print(words, file = other_file)
except IOError as err:
print('File error:' + str(err)) //詳細定製錯誤,把IOError轉化爲str字符串,打印
finally:
man_file.close() //close 關閉保存
other_file.close()
if 'data' in locals():
用locals
檢查當前作用域中的所有名
- 或者
with
模式,替代手動關閉open/clsoe
,
with/as
context manager 自動在結尾管理對象
file = open('foo.txt')
...
close(file)
with open('foo.txt') as file:
...
try:
with open('man_data.txt',w) as man_file, open('other_data.txt',w): as other_file:
print(role, file=man_file)
print(words, file = other_file)
函數中添加文件保存
引入sys.stdout
模塊,保存爲標準輸出
def print_lol(the_list, indent=False, level=0, fn=sys.stdout)
for each_item in the_list:
if isinstance(each_item, list):
print_lol(each_item, indent, level+1, fn)
else:
if indent:
for tab_stop in range(level):
print("\t", end="", file=fn)
print(each_item, file=fn)
pickle內置數據庫 dump/load
內部保存數據,二進制模式:'wb','rb'
dump
和load
讀取存儲
import pickle
a_list = []
...
with open ('mydata.pickle', 'wb') as mysavedata: //二進制寫入wb模式打開
pickle.dump([1,2,'three'], mysavedata) //pickle.dump儲存
with open ('mydata.pickle', 'rb') as myrestoredata: //二進制讀取rb模式打開
a_list = pickle.load(myrestoredata) //pickle.load讀取
print a_list
處理數據
data.strip().split(',')
方法串鏈 method chaining 左到右
- 先strip()
把數據空白去掉
- 在split(',')
進行分割
print(sotred(james))
函數串鏈 funciton chaining 右到左
數據處理函數
sort()
原地排序
sorted()
創建副本 排序
推導列表 list comprehension 減少列表a到列表b的轉換
name= [ interation for item in items] p181
mins = [1,2,3]
secs = [ m*60 for m in mins]
clean_mikey=[]
for each_t in mikey:
clean_mikey.append(sanitize(each_t))
簡寫成
clean_mikey = [sanitize(each_t) for each_t in mikey]
集合 不允許重複值
set()
print(sorted(set([sanitize(t) for t in sarh]))[0:3])
輸出前3,集合去重
字典 key/value
cless={}
或者 pain = dict()
定義類 class
使用class創建對象, 包含__init__
特殊方法,如何初始化對象
self
用於分辨對象
Athlete().__init__(a)
class Athlete:
def __init__(self, a_name, a_dot=None, a_time=[]):
self.name = a_name
self.dob = a_dob
self.times = a_times
def how_bif(self)
json格式
import json
names = ['a','b',['asd','ads'],'d']
to_transfer = json.dump(names) //將列表轉化爲json
from_transfer = json.load(to_transfer) //將json轉化爲列表
數據庫 內置sqlite3數據庫管理系統
import sqlite3
connection = sqlite3.connect('test.sqlite') //建立連接
cursor = connection.cursor //創建遊標
cursor.execute("""SELECT DATA('now')""") //操作
connection.commit() //執行 關閉
connection.close()