零基础实践深度学习之Python基础
零基礎實踐深度學習之Python基礎
- Python數據結構
- 數字
- 字符串
- 列表
- 元組
- 字典
- Python面向對象
- Python JSON
- Python異常處理
- Python文件操作
- 常見Linux命令
- gzip:
- tar:
- zip和unzip
Python數據結構
數字、字符串、列表、元組、字典
數字
Python Number 數據類型用于存儲數值。
Python Number 數據類型用于存儲數值,包括整型、長整型、浮點型、復數。
(1)Python math 模塊:Python 中數學運算常用的函數基本都在 math 模塊
import mathprint(math.ceil(4.1)) #返回數字的上入整數print(math.floor(4.9)) #返回數字的下舍整數print(math.fabs(-10)) #返回數字的絕對值print(math.sqrt(9)) #返回數字的平方根print(math.exp(1)) #返回e的x次冪 5 4 10.0 3.0 2.718281828459045(2)Python隨機數
首先import random,使用random()方法即可隨機生成一個[0,1)范圍內的實數
import random ran = random.random() print(ran) 0.4536929444397546randint()生成一個隨機整數
ran = random.randint(1,20) print(ran) 18字符串
字符串連接:+
a = "Hello " b = "World " print(a + b) Hello World重復輸出字符串:*
print(a * 3) Hello Hello Hello通過索引獲取字符串中字符[]
print(a[0]) H字符串截取[:] 牢記:左閉右開
print(a[1:4]) ell判斷字符串中是否包含給定的字符: in, not in
print('e' in a) print('e' not in a) True Falsejoin():以字符作為分隔符,將字符串中所有的元素合并為一個新的字符串
new_str = '-'.join('Hello') print(new_str) H-e-l-l-o字符串單引號、雙引號、三引號
print('Hello World!') print("Hello World!")轉義字符 \
print("The \t is a tab") print('I\'m going to the movies') The is a tab I'm going to the movies三引號讓程序員從引號和特殊字符串的泥潭里面解脫出來,自始至終保持一小塊字符串的格式是所謂的WYSIWYG(所見即所得)格式的。
print('''I'm going to the movies''')html = ''' <HTML><HEAD><TITLE> Friends CGI Demo</TITLE></HEAD> <BODY><H3>ERROR</H3> <B>%s</B><P> <FORM><INPUT TYPE=button VALUE=Back ONCLICK="window.history.back()"></FORM> </BODY></HTML> ''' print(html) I'm going to the movies<HTML><HEAD><TITLE> Friends CGI Demo</TITLE></HEAD> <BODY><H3>ERROR</H3> <B>%s</B><P> <FORM><INPUT TYPE=button VALUE=Back ONCLICK="window.history.back()"></FORM> </BODY></HTML>列表
作用:類似其他語言中的數組
聲明一個列表,并通過下標或索引獲取元素
#聲明一個列表 names = ['jack','tom','tonney','superman','jay']#通過下標或索引獲取元素 print(names[0]) print(names[1]) jack tom #獲取最后一個元素 print(names[-1]) print(names[len(names)-1]) #獲取第一個元素 print(names[-5]) #遍歷列表,獲取元素 for name in names:print(name) #查詢names里面有沒有superman for name in names:if name == 'superman':print('有超人')break else:print('無超人') #更簡單的方法,來查詢names里有沒有superman if 'superman' in names:print('有超人') else:print('無超人')列表元素添加
#聲明一個空列表 girls = []#append(),末尾追加 girls.append('楊超越') print(girls) ['楊超越'] #extend(),一次添加多個。把一個列表添加到另一個列表 ,列表合并。 models = ['劉雯','奚夢瑤'] girls.extend(models) #girls = girls + models print(girls) ['楊超越', '劉雯', '奚夢瑤', '劉雯', '奚夢瑤'] #insert():指定位置添加 girls.insert(1,'虞書欣') print(girls)列表元素修改,通過下標找到元素,然后用=賦值
fruits = ['apple','pear','香蕉','pineapple','草莓'] print(fruits)fruits[-1] = 'strawberry' print(fruits) ['apple', 'pear', '香蕉', 'pineapple', '草莓'] ['apple', 'pear', '香蕉', 'pineapple', 'strawberry'] ''' 將fruits列表中的‘香蕉’替換為‘banana’ ''' for fruit in fruits:if '香蕉' in fruit:fruit = 'banana' print(fruits)for i in range(len(fruits)):if '香蕉' in fruits[i]:fruits[i] = 'banana'break print(fruits) ['apple', 'pear', '香蕉', 'pineapple', 'strawberry'] ['apple', 'pear', 'banana', 'pineapple', 'strawberry']列表元素刪除
words = ['cat','hello','pen','pencil','ruler'] del words[0] print(words) ['hello', 'pen', 'pencil', 'ruler'] words = ['cat','hello','pen','pencil','ruler'] words.remove('cat') print(words) ['hello', 'pen', 'pencil', 'ruler'] words = ['cat','hello','pen','pencil','ruler'] words.pop(0) print(words) ['hello', 'pen', 'pencil', 'ruler']列表切片
-
在Python中處理列表的部分元素,稱之為切片。
-
創建切片,可指定要使用的第一個元素和最后一個元素的索引。注意:左閉右開
-
將截取的結果再次存放在一個列表中,所以還是返回列表
列表排序
- 隨機生成10個不同的整數,并進行排序
上述代碼存在什么問題嗎?
import randomrandom_list = [] i = 0 while i < 10:ran = random.randint(1,20)if ran not in random_list:random_list.append(ran)i+=1 print(random_list) #默認升序 new_list = sorted(random_list) print(new_list)#降序 new_list = sorted(random_list,reverse =True) print(new_list)元組
與列表類似,元組中的內容不可修改
tuple1 = () print(type(tuple1)) <class 'tuple'> tuple2 = ('hello') print(type(tuple2)) <class 'str'>注意:元組中只有一個元素時,需要在后面加逗號!
tuple3 = ('hello',) print(type(tuple3)) <class 'tuple'>元組不能修改,所以不存在往元組里加入元素。
那作為容器的元組,如何存放元素?
import randomrandom_list = [] for i in range(10):ran = random.randint(1,20)random_list.append(ran) print(random_list)random_tuple = tuple(random_list) print(random_tuple) [14, 4, 2, 14, 13, 4, 12, 3, 7, 9] (14, 4, 2, 14, 13, 4, 12, 3, 7, 9)元組訪問
print(random_tuple) print(random_tuple[0]) print(random_tuple[-1]) print(random_tuple[1:-3]) print(random_tuple[::-1])元組的修改:
t1 = (1,2,3)+(4,5) print(t1) (1, 2, 3, 4, 5) t2 = (1,2) * 2 print(t2) (1, 2, 1, 2)元組的一些函數:
print(max(random_tuple)) print(min(random_tuple)) print(sum(random_tuple)) print(len(random_tuple)) 14 2 82 10字典
#定義一個空字典dict1 = {}dict2 = {'name':'楊超越','weight':45,'age':25} print(dict2['name']) 楊超越 #list可以轉成字典,但前提是列表中元素都要成對出現 dict3 = dict([('name','楊超越'),('weight',45)]) print(dict3) dict4 = {} dict4['name'] = '虞書欣' dict4['weight'] = 43 print(dict4) {'name': '虞書欣', 'weight': 43} dict4['weight'] = 44 print(dict4) {'name': '虞書欣', 'weight': 44} #字典里的函數 items() keys() values()dict5 = {'楊超越':165,'虞書欣':166,'上官喜愛':164} print(dict5.items()) for key,value in dict5.items():if value > 165:print(key) dict_items([('楊超越', 165), ('虞書欣', 166), ('上官喜愛', 164)]) 虞書欣 #values() 取出字典中所有的值,保存到列表中results = dict5.values() print(results) dict_values([165, 166, 164]) #求小姐姐的平均身高 heights = dict5.values() print(heights) total = sum(heights) avg = total/len(heights) print(avg) dict_values([165, 166, 164]) 165.0 names = dict5.keys() print(names) dict_keys(['楊超越', '虞書欣', '上官喜愛']) #print(dict5['趙小棠']) #若不存在“趙小棠”,會報錯KeyError print(dict5.get('趙小棠'))print(dict5.get('趙小棠',170)) #如果能夠取到值,則返回字典中的值,否則返回默認值170 None 170 dict6 = {'楊超越':165,'虞書欣':166,'上官喜愛':164} del dict6['楊超越'] print(dict6) {'虞書欣': 166, '上官喜愛': 164} result = dict6.pop('虞書欣') print(result) print(dict6) 166 {'上官喜愛': 164}Python面向對象
定義一個類Animals:
(1)init()定義構造函數,與其他面向對象語言不同的是,Python語言中,會明確地把代表自身實例的self作為第一個參數傳入
(2)創建一個實例化對象 cat,init()方法接收參數
(3)使用點號 . 來訪問對象的屬性。
class Animal:def __init__(self,name):self.name = nameprint('動物名稱實例化')def eat(self):print(self.name +'要吃東西啦!')def drink(self):print(self.name +'要喝水啦!')cat = Animal('miaomiao') print(cat.name) cat.eat() cat.drink() class Person: def __init__(self,name):self.name = nameprint ('調用父類構造函數')def eat(self):print('調用父類方法')class Student(Person): # 定義子類def __init__(self):print ('調用子類構造方法')def study(self):print('調用子類方法')s = Student() # 實例化子類 s.study() # 調用子類的方法 s.eat() # 調用父類方法Python JSON
JSON(JavaScript Object Notation) 是一種輕量級的數據交換格式,易于人閱讀和編寫。
json.dumps 用于將 Python 對象編碼成 JSON 字符串。
import json data = [ { 'b' : 2, 'd' : 4, 'a' : 1, 'c' : 3, 'e' : 5 } ] json = json.dumps(data) print(json) [{"b": 2, "d": 4, "a": 1, "c": 3, "e": 5}]為了提高可讀性,dumps方法提供了一些可選的參數。
sort_keys=True表示按照字典排序(a到z)輸出。
indent參數,代表縮進的位數
separators參數的作用是去掉,和:后面的空格,傳輸過程中數據越精簡越好
import json data = [ { 'b' : 2, 'd' : 4, 'a' : 1, 'c' : 3, 'e' : 5 } ] json = json.dumps(data, sort_keys=True, indent=4,separators=(',', ':')) print(json) [{"a":1,"b":2,"c":3,"d":4,"e":5} ]json.loads 用于解碼 JSON 數據。該函數返回 Python 字段的數據類型。
import json jsonData = '{"a":1,"b":2,"c":3,"d":4,"e":5}' text = json.loads(jsonData) #將string轉換為dict print(text) {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}Python異常處理
當Python腳本發生異常時我們需要捕獲處理它,否則程序會終止執行。
捕捉異常可以使用try/except語句。
try/except語句用來檢測try語句塊中的錯誤,從而讓except語句捕獲異常信息并處理。
try:fh = open("/home/aistudio1/data/testfile01.txt", "w")fh.write("這是一個測試文件,用于測試異常!!") except IOError:print('Error: 沒有找到文件或讀取文件失敗') else:print ('內容寫入文件成功')fh.close() Error: 沒有找到文件或讀取文件失敗finally中的內容,退出try時總會執行
try:f = open("/home/aistudio/data/testfile02.txt", "w")f.write("這是一個測試文件,用于測試異常!!") finally:print('關閉文件')f.close() 關閉文件Python文件操作
在 Python 中,讀寫文件有 3 個步驟:
(1)調用 open()函數,返回一個 File 對象。
(2)調用 File 對象的 read()或 write()方法。
(3)調用 File 對象的 close()方法,關閉該文件。
f = open("work/test.txt",'w') #變量名=open(文件路徑和文件名,打開模式) 模式:w:寫,r:只寫;a:追加寫 f.write("hello") f.write("\npython") f.close() f = open("work/test.txt",'r') #變量名=open(文件路徑和文件名,打開模式) 模式:w:寫,r:只寫;a:追加寫 # print(f.read()) #f.read():從文件中讀入整個文件內容,結果為字符串 # print(f.readline()) #f.readline():從文件中讀入一行內容,結果為字符串 print(f.readlines()) #f.readlines():從文件中讀取所有行,以每行元素形成一個列表 f.close() ['hello\n', 'python']使用open()函數打開的文件對象,必須手動進行關閉,Python 垃圾回收機制無法自動回收打開文件所占用的資源。
因此,推薦以下寫法:
with open("work/test.txt",'a') as f:f.write("PadddlePaddle")f.write("\nokokok")常見Linux命令
!ls /home aistudio !ls ./ ls -l !pwdcp :復制文件或目錄
!cp test.txt ./test_copy.txtmv:移動文件與目錄,或修改文件與目錄的名稱
!mv /home/aistudio/work/test_copy.txt /home/aistudio/data/rm :移除文件或目錄
!rm /home/aistudio/data/test_copy.txt很多大型文件或者數據從服務器上傳或者下載的時候都需要打包和壓縮解壓,這時候知道壓縮和解壓的各種命令是很有必要的。
常見的壓縮文件后綴名有.tar.gz,.gz,和.zip,下面來看看在Linux上它們分別的解壓和壓縮命令。
gzip:
linux壓縮文件中最常見的后綴名即為.gz,gzip是用來壓縮和解壓.gz文件的命令。
常用參數:
-d或--decompress或--uncompress:解壓文件; -r或--recursive:遞歸壓縮指定文件夾下的文件(該文件夾下的所有文件被壓縮成單獨的.gz文件); -v或--verbose:顯示指令執行過程。 注:gzip命令只能壓縮單個文件,而不能把一個文件夾壓縮成一個文件(與打包命令的區別)。 #會將文件壓縮為文件 test.txt.gz,原來的文件則沒有了,解壓縮也一樣 !gzip /home/aistudio/work/test.txt !gzip -d /home/aistudio/test.gztar:
tar本身是一個打包命令,用來打包或者解包后綴名為.tar。配合參數可同時實現打包和壓縮。
常用參數:
-c或--create:建立新的備份文件; -x或--extract或--get:從備份文件中還原文件; -v:顯示指令執行過程; -f或--file:指定備份文件; -C:指定目的目錄; -z:通過gzip指令處理備份文件; -j:通過bzip2指令處理備份文件。最常用的是將tar命令與gzip命令組合起來,直接對文件夾先打包后壓縮:
!tar -zcvf /home/aistudio/work/test.tar.gz /home/aistudio/work/test.txt !tar -zxvf /home/aistudio/work/test.tar.gzzip和unzip
zip命令和unzip命令用在在Linux上處理.zip的壓縮文件。
常用參數
zip:
-v:顯示指令執行過程; -m:不保留原文件; -r:遞歸處理。unzip:
-v:顯示指令執行過程; -d:解壓到指定目錄。 !zip -r /home/aistudio/work/test.zip /home/aistudio/work/test.txt !unzip /home/aistudio/work/test.zip總結
以上是生活随笔為你收集整理的零基础实践深度学习之Python基础的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Markdown编辑器】LaTeX公式
- 下一篇: PaddlePaddle飞浆开启人工智能