Python是一種跨平臺的計算機程序設計語言。是一種面向對象的動態類型語言,最初被設計用於編寫自動化腳本(shell),隨着版本的不斷更新和語言新功能的添加,愈來愈多被用於獨立的、大型項目的開發。python
圖片在此以前,我已經寫了如下幾篇AI基礎的快速入門,本篇文章講解python語言的基礎部分,也是後續內容的基礎。git
已發佈:github
AI 基礎:Numpy 簡易入門算法
AI 基礎:Pandas 簡易入門shell
AI 基礎:Scipy(科學計算庫) 簡易入門數組
AI基礎:數據可視化簡易入門(matplotlib和seaborn)數據結構
後續持續更新app
本文代碼能夠在github下載:ide
https://github.com/fengdu78/Data-Science-Notes/tree/master/1.python-basic函數
文件名:Python_Basic.ipynb
在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 math
print (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 time
now = 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 datetime
someDay = datetime.date(1999,2,10)
anotherDay = datetime.date(1999,2,15)
deltaDay = anotherDay - someDay
deltaDay.days
5 還有其餘一些datetime格式 ![](https://s4.51cto.com/images/blog/202012/26/f7c28686d232a34ae6f52e16e3f3beec.bmp?x-oss-process=image/watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=) * 查看變量類型
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] 列表索引和切片
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:
break
print (i)
1 2
for i in range(1, 5):
if i == 3:
continue
print (i)
1 2 4
for i in range(1, 5):
if i == 3:
pass
print (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**2
test_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+n
test_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 + '=' + v
test_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 x
else:
return -x
my_abs(-9)
9 能夠沒有return
def filter_fruit(someList, d):
for i in someList:
if i == d:
someList.remove(i)
else:
pass
print (filter_fruit(fruits, 'Melon'))
print (fruits)
None ['Apple', 'Banana', 'Grape'] 多個返回值的狀況
def test(i, j):
k = i * j
return i, j, k
a , 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,其它被判斷爲True
filter(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 power
myF = 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中的註釋通常用?查看幫助