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