日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

AI 基础:Python 简易入门

發布時間:2025/3/8 python 41 豆豆
生活随笔 收集整理的這篇文章主要介紹了 AI 基础:Python 简易入门 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

0.導語

Python是一種跨平臺的計算機程序設計語言。是一種面向對象的動態類型語言,最初被設計用于編寫自動化腳本(shell),隨著版本的不斷更新和語言新功能的添加,越來越多被用于獨立的、大型項目的開發。

在此之前,我已經寫了以下幾篇AI基礎的快速入門,本篇文章講解python語言的基礎部分,也是后續內容的基礎。

已發布:

AI 基礎:Numpy 簡易入門

AI 基礎:Pandas 簡易入門

AI 基礎:Scipy(科學計算庫) 簡易入門

AI基礎:數據可視化簡易入門(matplotlib和seaborn)

后續持續更新

本文代碼可以在github下載:

https://github.com/fengdu78/Data-Science-Notes/tree/master/1.python-basic

文件名:Python_Basic.ipynb

1 Python數據類型

1.1 字符串

在Python中用引號引起來的字符集稱之為字符串,比如:'hello'、"my Python"、"2+3"等都是字符串 Python中字符串中使用的引號可以是單引號、雙引號跟三引號

print ('hello world!') hello world! c = 'It is a "dog"!' print (c) It is a "dog"! c1= "It's a dog!" print (c1) It's a dog! c2 = """hello world !""" print (c2) hello world !
  • 轉義字符''

轉義字符\可以轉義很多字符,比如\n表示換行,\t表示制表符,字符\本身也要轉義,所以\ \表示的字符就是\

print ('It\'s a dog!') print ("hello world!\nhello Python!") print ('\\\t\\') It's a dog! hello world! hello Python! \ \

原樣輸出引號內字符串可以使用在引號前加r

print (r'\\\t\\') \\\t\\
  • 子字符串及運算

s = 'Python' print( 'Py' in s) print( 'py' in s) True False

取子字符串有兩種方法,使用[]索引或者切片運算法[:],這兩個方法使用面非常廣

print (s[2]) t print (s[1:4]) yth
  • 字符串連接與格式化輸出

word1 = '"hello"' word2 = '"world"' sentence = word1.strip('"') + ' ' + word2.strip('"') + '!'print( 'The first word is %s, and the second word is %s' %(word1, word2)) print (sentence) The first word is "hello", and the second word is "world" hello world!

1.2 整數與浮點數

整數

Python可以處理任意大小的整數,當然包括負整數,在程序中的表示方法和數學上的寫法一模一樣

i = 7 print (i) 7 7 + 3 10 7 - 3 4 7 * 3 21 7 ** 3 343 7 / 3#Python3之后,整數除法和浮點數除法已經沒有差異 2.3333333333333335 7 % 3 1 7//3 2 浮點數7.0 / 3 2.3333333333333335 3.14 * 10 ** 2 314.0

其它表示方法

0b1111 15 0xff 255 1.2e-5 1.2e-05

更多運算

import mathprint (math.log(math.e)) # 更多運算可查閱文檔 1.0

1.3 布爾值

True True False False True and False False True or False True not True False True + False 1 18 >= 6 * 3 or 'py' in 'Python' True 18 >= 6 * 3 and 'py' in 'Python' False 18 >= 6 * 3 and 'Py' in 'Python' True

1.4 日期時間

import timenow = time.strptime('2016-07-20', '%Y-%m-%d') print (now) time.struct_time(tm_year=2016, tm_mon=7, tm_mday=20, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=202, tm_isdst=-1) time.strftime('%Y-%m-%d', now) '2016-07-20' import datetimesomeDay = datetime.date(1999,2,10) anotherDay = datetime.date(1999,2,15) deltaDay = anotherDay - someDay deltaDay.days 5

還有其他一些datetime格式

  • 查看變量類型

type(None) NoneType type(1.0) float type(True) bool s="NoneType" type(s) str
  • 類型轉換

str(10086) '10086' ?float() float(10086) 10086.0 int('10086') 10086 complex(10086) (10086+0j)

2 Python數據結構

列表(list)、元組(tuple)、集合(set)、字典(dict)

2.1 列表(list)

用來存儲一連串元素的容器,列表用[]來表示,其中元素的類型可不相同。

mylist= [0, 1, 2, 3, 4, 5] print (mylist) [0, 1, 2, 3, 4, 5]

列表索引和切片

# 索引從0開始,含左不含右 print ('[4]=', mylist[4]) print ('[-4]=', mylist[-4]) print ('[0:4]=', mylist[0:4]) print ('[:4]=', mylist[:4])#dddd print( '[4:]=', mylist[4:]) print ('[0:4:2]=', mylist[0:4:2]) print ('[-5:-1:]=', mylist[-5:-1:]) print ('[-2::-1]=', mylist[-2::-1]) [4]= 4 [-4]= 2 [0:4]= [0, 1, 2, 3] [:4]= [0, 1, 2, 3] [4:]= [4, 5] [0:4:2]= [0, 2] [-5:-1:]= [1, 2, 3, 4] [-2::-1]= [4, 3, 2, 1, 0]

修改列表

mylist[3] = "小月" print (mylist[3])mylist[5]="小楠" print (mylist[5])mylist[5]=19978 print (mylist[5])小月 小楠 19978 print (mylist) [0, 1, 2, '小月', 4, 19978]

插入元素

mylist.append('han') # 添加到尾部 mylist.extend(['long', 'wan']) print (mylist) [0, 1, 2, '小月', 4, 19978, 'han', 'long', 'wan'] scores = [90, 80, 75, 66] mylist.insert(1, scores) # 添加到指定位置 mylist [0, [90, 80, 75, 66], 1, 2, '小月', 4, 19978, 'han', 'long', 'wan'] a=[]

刪除元素

print (mylist.pop(1)) # 該函數返回被彈出的元素,不傳入參數則刪除最后一個元素 print (mylist) [90, 80, 75, 66] [0, 1, 2, '小月', 4, 19978, 'han', 'long', 'wan']

判斷元素是否在列表中等

print( 'wan' in mylist) print ('han' not in mylist) True False mylist.count('wan') 1 mylist.index('wan') 8

range函數生成整數列表

print (range(10)) print (range(-5, 5)) print (range(-10, 10, 2)) print (range(16, 10, -1)) range(0, 10) range(-5, 5) range(-10, 10, 2) range(16, 10, -1)

2.2 元組(tuple)

元組類似列表,元組里面的元素也是進行索引計算。列表里面的元素的值可以修改,而元組里面的元素的值不能修改,只能讀取。元組的符號是()。

studentsTuple = ("ming", "jun", "qiang", "wu", scores) studentsTuple ('ming', 'jun', 'qiang', 'wu', [90, 80, 75, 66]) try:studentsTuple[1] = 'fu' except TypeError:print ('TypeError') TypeError scores[1]= 100 studentsTuple ('ming', 'jun', 'qiang', 'wu', [90, 100, 75, 66]) 'ming' in studentsTuple True studentsTuple[0:4] ('ming', 'jun', 'qiang', 'wu') studentsTuple.count('ming') 1 studentsTuple.index('jun') 1 len(studentsTuple) 5

2.3 集合(set)

Python中集合主要有兩個功能,一個功能是進行集合操作,另一個功能是消除重復元素。集合的格式是:set(),其中()內可以是列表、字典或字符串,因為字符串是以列表的形式存儲的

studentsSet = set(mylist) print (studentsSet) {0, 1, 2, 'han', 4, '小月', 19978, 'wan', 'long'} studentsSet.add('xu') print (studentsSet) {0, 1, 2, 'han', 4, '小月', 19978, 'wan', 'long', 'xu'} studentsSet.remove('xu') print (studentsSet) {0, 1, 2, 'han', 4, '小月', 19978, 'wan', 'long'} mylist.sort()#會出錯 ---------------------------------------------------------------------------TypeError Traceback (most recent call last)<ipython-input-69-7309caa8a1d6> in <module>() ----> 1 mylist.sort()TypeError: '<' not supported between instances of 'str' and 'int' a = set("abcnmaaaaggsng") print ('a=', a) a= {'b', 'a', 'm', 'c', 'g', 's', 'n'} b = set("cdfm") print ('b=', b) b= {'m', 'd', 'c', 'f'} #交集 x = a & b print( 'x=', x) x= {'m', 'c'} #并集 y = a | b print ('y=', y) #差集 z = a - b print( 'z=', z) #去除重復元素 new = set(a) print( z) y= {'b', 'a', 'f', 'd', 'm', 'c', 'g', 's', 'n'} z= {'b', 'a', 'g', 's', 'n'} {'b', 'a', 'g', 's', 'n'}

2.4字典(dict)

Python中的字典dict也叫做關聯數組,用大括號{}括起來,在其他語言中也稱為map,使用鍵-值(key-value)存儲,具有極快的查找速度,其中key不能重復。

k = {"name":"weiwei", "home":"guilin"} print (k["home"]) guilin print( k.keys()) print( k.values()) dict_keys(['name', 'home']) dict_values(['weiwei', 'guilin'])

添加、修改字典里面的項目

k["like"] = "music" k['name'] = 'guangzhou' print (k) {'name': 'guangzhou', 'home': 'guilin', 'like': 'music'} k.get('edu', -1) # 通過dict提供的get方法,如果key不存在,可以返回None,或者自己指定的value -1

刪除key-value元素

k.pop('like') print (k) {'name': 'guangzhou', 'home': 'guilin'}

2.5 列表、元組、集合、字典的互相轉換

type(mylist) list tuple(mylist) (0, 1, 2, '小月', 4, 19978, 'han', 'long', 'wan') list(k) ['name', 'home'] zl = zip(('A', 'B', 'C'), [1, 2, 3, 4]) # zip可以將列表、元組、集合、字典‘縫合’起來 print (zl) print (dict(zl)) <zip object at 0x0000015AFAA612C8> {'A': 1, 'B': 2, 'C': 3}

3 Python控制流

在Python中通常的情況下程序的執行是從上往下執行的,而某些時候我們為了改變程序的執行順序,使用控制流語句控制程序執行方式。Python中有三種控制流類型:順序結構、分支結構、循環結構。

另外,Python可以使用分號";"分隔語句,但一般是使用換行來分隔;語句塊不用大括號"{}",而使用縮進(可以使用四個空格)來表示

3.1 順序結構

s = '7' num = int(s) # 一般不使用這種分隔方式 num -= 1 # num = num - 1 num *= 6 # num = num * 6 print (num) 36

3.2 分支結構:Python中if語句是用來判斷選擇執行哪個語句塊的

if <True or Flase表達式>:

執行語句塊

elif <True or Flase表達式>:

執行語句塊

else:? ? ? ?# 都不滿足

執行語句塊

#elif子句可以有多條,elif和else部分可省略

salary = 1000 if salary > 10000:print ("Wow!!!!!!!") elif salary > 5000:print ("That's OK.") elif salary > 3000:print ("5555555555") else:print ("..........") ..........

3.3 循環結構

while 循環

while <True or Flase表達式>:

循環執行語句塊

else:? ? ? ? ?# 不滿足條件

執行語句塊

#else部分可以省略

a = 1 while a < 10:if a <= 5:print (a)else:print ("Hello")a = a + 1 else:print ("Done") 1 2 3 4 5 Hello Hello Hello Hello Done
  • for 循環 for (條件變量) in (集合):

    執行語句塊

“集合”并不單指set,而是“形似”集合的列表、元組、字典、數組都可以進行循環

條件變量可以有多個

heights = {'Yao':226, 'Sharq':216, 'AI':183} for i in heights:print (i, heights[i]) Yao 226 Sharq 216 AI 183 for key, value in heights.items():print(key, value) Yao 226 Sharq 216 AI 183 total = 0 for i in range(1, 101):total += i#total=total+i print (total) 5050

3.4 break、continue和pass

break:跳出循環

continue:跳出當前循環,繼續下一次循環

pass:占位符,什么也不做

for i in range(1, 5):if i == 3:breakprint (i) 1 2 for i in range(1, 5):if i == 3:continueprint (i) 1 2 4 for i in range(1, 5):if i == 3:passprint (i) 1 2 3 4

3.5 列表生成式

三種形式

  • [<表達式> for (條件變量) in (集合)]

  • [<表達式> for (條件變量) in (集合) if <'True or False'表達式>]

  • [<表達式> if <'True or False'表達式> else <表達式> ?for (條件變量) in (集合) ]

fruits = ['"Apple', 'Watermelon', '"Banana"'] [x.strip('"') for x in fruits] ['Apple', 'Watermelon', 'Banana'] # 另一種寫法 test_list=[] for x in fruits:x=x.strip('"')test_list.append(x) test_list ['Apple', 'Watermelon', 'Banana'] [x ** 2 for x in range(21) if x%2] [1, 9, 25, 49, 81, 121, 169, 225, 289, 361] # 另一種寫法 test_list=[] for x in range(21):if x%2:x=x**2test_list.append(x) test_list [1, 9, 25, 49, 81, 121, 169, 225, 289, 361] [m + n for m in 'ABC' for n in 'XYZ'] ['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ'] # 另一種寫法 test_list=[] for m in 'ABC':for n in 'XYZ':x=m+ntest_list.append(x) test_list ['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ'] d = {'x': 'A', 'y': 'B', 'z': 'C' } [k + '=' + v for k, v in d.items()] ['x=A', 'y=B', 'z=C'] # 另一種寫法 test_list=[] for k, v in d.items():x=k + '=' + vtest_list.append(x) test_list ['x=A', 'y=B', 'z=C']

4 Python函數

函數是用來封裝特定功能的實體,可對不同類型和結構的數據進行操作,達到預定目標。

4.1 調用函數

  • Python內置了很多有用的函數,我們可以直接調用,進行數據分析時多數情況下是通過調用定義好的函數來操作數據的

str1 = "as" int1 = -9 print (len(str1)) print (abs(int1)) 2 9 fruits = ['Apple', 'Banana', 'Melon'] fruits.append('Grape') print (fruits) ['Apple', 'Banana', 'Melon', 'Grape']

4.2 定義函數

當系統自帶函數不足以完成指定的功能時,需要用戶自定義函數來完成。def 函數名():函數內容 函數內容 <return 返回值>

def my_abs(x):if x >= 0:return xelse:return -xmy_abs(-9) 9

可以沒有return

def filter_fruit(someList, d):for i in someList:if i == d:someList.remove(i)else:passprint (filter_fruit(fruits, 'Melon')) print (fruits) None ['Apple', 'Banana', 'Grape']

多個返回值的情況

def test(i, j):k = i * jreturn i, j, ka , b , c = test(4, 5) print (a, b , c) type(test(4, 5)) 4 5 20 tuple

4.3 高階函數

  • 把另一個函數作為參數傳入一個函數,這樣的函數稱為高階函數

函數本身也可以賦值給變量,函數與其它對象具有同等地位

myFunction = abs myFunction(-9) 9
  • 參數傳入函數

def add(x, y, f):return f(x) + f(y)add(7, -5, myFunction) 12
  • 常用高階函數

map/reduce: map將傳入的函數依次作用到序列的每個元素,并把結果作為新的list返回;reduce把一個函數作用在一個序列[x1, x2, x3...]上,這個函數必須接收兩個參數,reduce把結果繼續和序列的下一個元素做累積計算

myList = [-1, 2, -3, 4, -5, 6, 7] map(abs, myList) <map at 0x15afaa00630> from functools import reduce def powerAdd(a, b):return pow(a, 2) + pow(b, 2)reduce(powerAdd, myList) # 是否是計算平方和? 3560020598205630145296938

filter:filter()把傳入的函數依次作用于每個元素,然后根據返回值是True還是False決定保留還是丟棄該元素

def is_odd(x):return x % 3 # 0被判斷為False,其它被判斷為Truefilter(is_odd, myList) <filter at 0x15afa9f0588>

sorted: 實現對序列排序,默認情況下對于兩個元素x和y,如果認為x < y,則返回-1,如果認為x == y,則返回0,如果認為x > y,則返回1

默認排序:數字大小或字母序(針對字符串)

sorted(myList) [-5, -3, -1, 2, 4, 6, 7]

*練習:自定義一個排序規則函數,可將列表中字符串忽略大小寫地,按字母序排列,列表為['Apple', 'orange', 'Peach', 'banana']。提示:字母轉換為大寫的方法為some_str.upper(),轉換為小寫使用some_str.lower()

  • 返回函數: 高階函數除了可以接受函數作為參數外,還可以把函數作為結果值返回

def powAdd(x, y):def power(n):return pow(x, n) + pow(y, n)return powermyF = powAdd(3, 4) myF <function __main__.powAdd.<locals>.power> myF(2) 25
  • 匿名函數:高階函數傳入函數時,不需要顯式地定義函數,直接傳入匿名函數更方便

f = lambda x: x * x f(4) 16

等同于:

def f(x):return x * x map(lambda x: x * x, myList) <map at 0x15afaa1d0f0>

匿名函數可以傳入多個參數

reduce(lambda x, y: x + y, map(lambda x: x * x, myList)) 140

返回函數可以是匿名函數

def powAdd1(x, y):return lambda n: pow(x, n) + pow(y, n)lamb = powAdd1(3, 4) lamb(2) 25

其它

  • 標識符第一個字符只能是字母或下劃線,第一個字符不能出現數字或其他字符;標識符除第一個字符外,其他部分可以是字母或者下劃線或者數字,標識符大小寫敏感,比如name跟Name是不同的標識符。

  • Python規范:

  • 類標識符每個字符第一個字母大寫;

  • 對象\變量標識符的第一個字母小寫,其余首字母大寫,或使用下劃線'_' 連接;

  • 函數命名同普通對象。

  • 關鍵字

關鍵字是指系統中自帶的具備特定含義的標識符

# 查看一下關鍵字有哪些,避免關鍵字做自定義標識符 import keyword print (keyword.kwlist) ['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
  • 注釋

Python中的注釋一般用#進行注釋

  • 幫助

Python中的注釋一般用?查看幫助

往期精彩回顧 那些年做的學術公益-你不是一個人在戰斗適合初學者入門人工智能的路線及資料下載機器學習在線手冊深度學習在線手冊備注:加入本站微信群或者qq群,請回復“加群”加入知識星球(4500+用戶,ID:92416895),請回復“知識星球”

總結

以上是生活随笔為你收集整理的AI 基础:Python 简易入门的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。