2019-04(1)(Python学习)
9.1 迭代器
?
創建迭代器的3種方法:
方法一:
容器對象添加 __iter__() 和 __next__() 方法(Python 2.7 中是 next());__iter__() 返回迭代器對象本身 self,__next__() 則返回每次調用 next() 或迭代時的元素;
自定義一個迭代器:
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)方法二:
使用內建函數iter()可以從可迭代對象中獲得迭代器。示例:
1. li = [2,5,3,7,9,10] 2. it = iter(li) 3. print(next(it), end=' ') #2 4. print(next(it), end=' ') #5以此類推方法三:
利用生成器(generator),生成器通過yield語句快速生成迭代器,省略了復雜的__iter()__和__next()__方式
參考原文:https://blog.csdn.net/qq_42068900/article/details/80369029
9.2 生成器
創建生成器:
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?
9.3 打開文件
標準函數是:
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/
9.4 讀取文件
1:readlines()
?
2:readline()
?
3:read()
?
4:tell()
?
5:truncate()
?
6:seek()
9.5 寫入文件
1:write() 將字符串寫入文件
?
2:writelines() 寫入多行數據
?
9.6 關閉和刷新文件
?1:close() 關閉文件函數
2:flush() 刷新文件
12.1 圖像的處理
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()13.3 操作MYSQL數據庫
?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()刪除后結果:
7、遇到的問題
期間遇到一個問題:<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等內容,以及數據處理部分內容。下周準備學習數據處理、數據分析兩章內容,進行簡單的數據分析。
轉載于:https://www.cnblogs.com/lifengB511/p/10700989.html
總結
以上是生活随笔為你收集整理的2019-04(1)(Python学习)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 库乐队怎么玩
- 下一篇: python框架源码学习