建立迭代器的3種方法:python
方法一:mysql
容器對象添加 __iter__() 和 __next__() 方法(Python 2.7 中是 next());__iter__() 返回迭代器對象自己 self,__next__() 則返回每次調用 next() 或迭代時的元素;sql
自定義一個迭代器:數據庫
1. class Contain: 2. def __init__(self,start,end): 3. self.start = start #self.start既是開始位置,也是記錄位置的狀態 4. self.end = end 5. def __iter__(self): 6. print('調用iter方法!') 7. return self #/__iter()__返回自身self 8. def __next__(self): 9. if self.start < self.end: 10. i = self.start 11. self.start += 1 12. return i 13. else: 14. raise StopIteration 15. Con = Contain(0,5) 16. for i in Con: 17. print(i)
方法二:canvas
使用內建函數iter()能夠從可迭代對象中得到迭代器。示例:app
1. li = [2,5,3,7,9,10] 2. it = iter(li) 3. print(next(it), end=' ') #2 4. print(next(it), end=' ') #5以此類推
方法三:ide
利用生成器(generator),生成器經過yield語句快速生成迭代器,省略了複雜的__iter()__和__next()__方式函數
參考原文:https://blog.csdn.net/qq_42068900/article/details/80369029oop
建立生成器:學習
1:generator 第一種建立方式(推導式):
輸入:
1. nums = (x for x in range(10)) 2. print(nums) #<generator object <genexpr> at 0x0000004590AB9938> 生成器類型 3. for i in nums: 4. print(i, end=' ') #0 1 2 3 4 5 6 7 8 9
輸出:
runfile('C:/Users/lf/Desktop/Python/Python練習/迭代器和生成器.py', wdir='C:/Users/lf/Desktop/Python/Python練習')
<generator object <genexpr> at 0x000002899B831360>
0 1 2 3 4 5 6 7 8 9
2:第二種建立方式(斐波那契數列):
輸入:
1. fibs = [] 2. def Fib(): 3. for i in range(100): 4. if i > 1: 5. fibs.append(fibs[i-2]+fibs[i-1]) 6. else: 7. fibs.append(1) 8. yield fibs[i] #print換成yield ,每次生成一個值 9. fibnaqi = Fib() 10. print(fibnaqi.__next__()) #1 11. print(next(fibnaqi)) #1 12. print(next(fibnaqi)) #2 13. print(next(fibnaqi)) #3 14. print(next(fibnaqi)) #5 15. print(next(fibnaqi)) #8 16. print(next(fibnaqi)) #13
輸出:
runfile('C:/Users/lf/Desktop/Python/Python練習/迭代器和生成器.py', wdir='C:/Users/lf/Desktop/Python/Python練習')
1 1 2 3 5 8 13
標準函數是:
open(filename,mode=’r’,buffering=-1,encoding=None, errors=None, newline=None, closefd=True, opener=None)
常見問題:
Python中遇到"UnicodeDecodeError: ‘gbk’ codec can’t decode bytes in position 2-3: illegal multibyte sequence"之類的編碼或解碼的錯誤時如何處理。
如何解決,參考原文:https://www.crifan.com/summary_python_unicodedecode_error_possible_reasons_and_solutions/
1:readlines()
2:readline()
3:read()
4:tell()
5:truncate()
6:seek()
1:write() 將字符串寫入文件
2:writelines() 寫入多行數據
1:close() 關閉文件函數
2:flush() 刷新文件
1、下載和安裝Pillow
方法一:
方法二:
2、加載圖像文件
示例一:
示例二:
from tkinter import * from PIL import Image, ImageTk #建立主窗口 win = Tk() win.title(string="加載圖像文件") imgFile1 = Image.open(r'C:\Users\lf\Desktop\Python\01.bmp') imgFile2 = Image.open(r'C:\Users\lf\Desktop\Python\02.jpg') imgFile3 = Image.open(r'C:\Users\lf\Desktop\Python\03.tif') imgFile4 = Image.open(r'C:\Users\lf\Desktop\Python\04.gif') img1 = ImageTk.PhotoImage(imgFile1) img2 = ImageTk.PhotoImage(imgFile2) img3 = ImageTk.PhotoImage(imgFile3) img4 = ImageTk.PhotoImage(imgFile4) canvas = Canvas(win, width=850,height=500) canvas.create_image(0, 0, image=img1, anchor=NW) canvas.create_image(450, 0, image=img2, anchor=NW) canvas.create_image(0, 250, image=img3, anchor=NW) canvas.create_image(450, 250, image=img4, anchor=NW) canvas.pack(fill = BOTH) #開始程序循環 win.mainloop()
3、複製與粘貼圖像
image模塊的copy()方法,來複制該圖像,copy();
image模塊的paste()方法,來粘貼該圖像,paste(image, box);
image模塊的crop()方法,剪切該圖像中的一個矩形方塊,crop(box)。
示例:
from tkinter import * from PIL import Image, ImageTk #建立主窗口 win = Tk() win.title(string="複製與粘貼圖像") #打開圖像文件 imgFile = Image.open(r'C:\Users\lf\Desktop\Python\test02.jpg') #建立第一個圖像實例變量 img1 = ImageTk.PhotoImage(imgFile) #讀取圖像文件的寬和高 width, height = imgFile.size #設置剪切下的區塊範圍 box1 = (0, 0, width, int(height/2)) #將圖像的上半部分剪切下來 part = imgFile.crop(box1) #將剪切下的部分旋轉 part = part.transpose(Image.ROTATE_180) #將剪切下,處理後的部分,粘貼 imgFile.paste(part, box1) #建立第二個圖像實例變量 img2 = ImageTk.PhotoImage(imgFile) #建立Label控件,來顯示圖像 label1 = Label(win, width=400, height=400, image=img1, borderwidth=1) label2 = Label(win, width=400, height=400, image=img2, borderwidth=1) label1.pack(side= LEFT) label2.pack(side= LEFT) #開始循環程序 win.mainloop()
4、圖像的幾何轉換
(1)改變圖像的大小:使用resize()方法,語法格式爲resize((width, height));
(2)旋轉圖像:使用rotate()方法,語法格式爲rotate(angle);
(3)顛倒圖像:使用transpose()方法,語法格式爲transpose(method)。
示例:
from tkinter import * from PIL import Image, ImageTk #建立主窗口 win = Tk() win.title(string="圖像的幾何轉換") #打開圖像文件 imgFile1 = Image.open(r'C:\Users\lf\Desktop\Python\test1.jpg') #建立第一個圖像實例變量 img1 = ImageTk.PhotoImage(imgFile1) #建立Label1控件,來顯示原始圖像 label1 = Label(win, width=300, height=400, image=img1) label1.pack(side = LEFT) #旋轉圖像成45°角 imgFile2 = imgFile1.rotate(45) img2 = ImageTk.PhotoImage(imgFile2) #建立Label2控件,來顯示圖像 label2 = Label(win, width=300, height=400, image=img2) label2.pack(side = LEFT) #旋轉圖像成90°角 imgFile3 = imgFile1.transpose(Image.ROTATE_90) img3 = ImageTk.PhotoImage(imgFile3) #建立Label3控件,來顯示圖像 label3 = Label(win, width=300, height=400, image=img3) label3.pack(side = LEFT) #改變圖像爲四分之一大小 width, height = imgFile1.size imgFile4 = imgFile1.resize((int(width/2),int(height/2))) img4 = ImageTk.PhotoImage(imgFile4) #建立Label3控件,來顯示圖像 label4 = Label(win, width=300, height=400, image=img4) label4.pack(side = LEFT) #開始循環程序 win.mainloop()
Python中操做MySQL的模塊是PyMySQL,在導入MySQL數據以前,須要安裝PyMySQL模塊。目前Python3.x僅支持PyMySQL,不支持MySQLdb。安裝PyMySQL,以下:
1、鏈接數據庫
代碼:
import pymysql #打開數據庫鏈接 db = pymysql.connect('localhost','lifeng','123456','shopping') #使用cursor()方法,建立一個遊標對象cursor cursor = db.cursor() #使用execute()方法執行SQL查詢 cursor.execute("SELECT VERSION()") #使用fetchone()方法獲取單條數據 data = cursor.fetchone() #打印數據庫版本號 print("Database version:%s" % data) #關閉數據庫 db.close()
2、在數據庫建立表
代碼:
import pymysql #打開數據庫鏈接 db = pymysql.connect('localhost','lifeng','123456','pymysql') #使用cursor()方法,建立一個遊標對象cursor cursor = db.cursor() #定義SQL語句 sql = """CREATE TABLE student4(id INT(10) NOT NULL UNIQUE,\ name CHAR(20) NOT NULL, age INT, sex CHAR(1))""" #使用execute()方法執行SQL查詢 cursor.execute(sql) #關閉數據庫 db.close()
3、在數據庫插入數據
代碼:
import pymysql import sys #打開數據庫鏈接 db = pymysql.connect('localhost','lifeng','123456','pymysql') #使用cursor()方法,建立一個遊標對象cursor cursor = db.cursor() #定義SQL語句 sql = "INSERT INTO student (id, name, age, sex) VALUES ('%d', '%s', '%d', '%s')" % (4 , '迪麗熱巴', 25, 'F') try: #執行插入數據語句 cursor.execute(sql) #提交到數據庫執行 db.commit() except: #若是發生錯誤,則回滾到插入操做以前 info = sys.exc_info() exc_type = info[0] exc_value = info[1] exc_traceback = info[2] print (exc_type, ":", exc_value) db.rollback() #回滾函數,回到錯誤操做以前,防止錯誤數據被插入。 #關閉數據庫 db.close()
插入後的結果:
4、查詢數據庫
代碼:
import pymysql #打開數據庫鏈接 db = pymysql.connect('localhost','lifeng','123456','pymysql') #使用cursor()方法,建立一個遊標對象cursor cursor = db.cursor() #定義SQL語句 sql = "SELECT * FROM student WHERE age > '%d'" % (23) try: #執行插入數據語句 cursor.execute(sql) results = cursor.fetchall() for row in results: id = row[0] name = row[1] age = row[2] sex = row[3] #打印查詢結果 print ("id=%d, name=%s, age=%d, sex=%s " % (id, name, age, sex)) except: #若是發生錯誤,則回滾到插入操做以前 print("錯誤:沒法查詢到數據!!!") #關閉數據庫 db.close()
查詢結果:
5、修改數據庫數據
代碼:
import pymysql #打開數據庫鏈接 db = pymysql.connect('localhost','lifeng','123456','pymysql') #使用cursor()方法,建立一個遊標對象cursor cursor = db.cursor() #定義SQL語句 sql = "UPDATE student SET age=age -1" try: #執行插入數據語句 cursor.execute(sql) #提交到數據庫執行 db.commit() except: db.rollback() #回滾函數,回到錯誤操做以前,防止錯誤數據被插入。 #關閉數據庫 db.close()
修改結果:
6、刪除數據庫數據
代碼:
import pymysql import sys #打開數據庫鏈接 db = pymysql.connect('localhost','lifeng','123456','pymysql') #使用cursor()方法,建立一個遊標對象cursor cursor = db.cursor() #定義SQL語句 sql = "DELETE FROM student WHERE sex = '%s'" % ('F') try: #執行插入數據語句 cursor.execute(sql) #提交到數據庫執行 db.commit() except: #若是發生錯誤,則回滾到插入操做以前 info = sys.exc_info() exc_type = info[0] exc_value = info[1] exc_traceback = info[2] print (exc_type, ":", exc_value) db.rollback() #回滾函數,回到錯誤操做以前,防止錯誤數據被插入。 #關閉數據庫 db.close()
刪除後結果:
七、遇到的問題
期間遇到一個問題:<class 'pymysql.err.OperationalError'> : (1142, "DELETE command denied to user 'lifeng'@'localhost' for table 'student'");
是由於「lifeng」這個數據庫沒有DELETE權限,須要設置權限,參考:https://blog.csdn.net/u014183172/article/details/78509017
——————————————————————————————————————————————————————————————————
初步瞭解numpy、pandas等內容,以及數據處理部份內容。下週準備學習數據處理、數據分析兩章內容,進行簡單的數據分析。