Python與機器學習前言——Python常用語法

爲什麼要學Python呢,爲了打好機器學習這場仗,需要有件趁手的兵器~這就是Python。
作爲可執行的僞代碼,實現起來的便利性就不多說了,關鍵是它的開源代碼多、環境好、有機器學習的庫:scikit-learn,當然,還有強大的字符串處理功能。
從《利用Python進行數據分析》附錄開始(基礎語法)從與常用的語言的區別開始談起。本文注重Python常用並與C語言有區別的語法。
1.

a = [1,2,3]
b = a
a.append(4)

此時a與b都等於[1,2.3,4]。即“=”表示a和b都指向同一個對象:[1,2,3]
2.
函數可對其參數進行改變操作。
C中函數調用的時候只是對形參的值進行復制使用,而Python的函數是純粹把形參拿過來了

def append_element(some_list,element)
    some_list.append(element)
    data = [1,2,3]
    append_element(data,4)

此時data就確確實實等於[1,2,3,4]了。
3.
isinstance:瞭解對象的類型

isinstance(5,int) #ture
isinstance(4.5,(int,float)) #true
isinstance(4.5,int) #flase

4.
isiterable:判斷某對象是否可迭代

isiterable([1,2,3]) #true
isiterable(5) #flase

5.
import
這個東西可將其他.py文件中的函數和定義好的變量引用在當前.py中,用這個就可以把各種庫引入進來了
from numpy import* # 把numpy庫中所有東西都引用過來
6.
is:用於判斷兩個引用是否指向同一個對象

a = [1,2,3]
b = a
c = list(a) #list可新建列表
a is b #true
a is not c #flase
a == c #true

7.
虛數虛部用 j 表示
cval = 1+2j
8.
字符串表示方法:

a = 'meachine learning'
b = 'big data'
c = """i love
meachine learning #用於帶換行
"""

Python字符串是不可以改變的,想修改字符串只能新建。
9.
字符串轉換與處理
許多Python對象都可以通過str函數轉換爲字符串:

a = 5.6
s = str(a) #s = '5.6'

字符串可以被當做某種序列類型(如列表、元組)來處理:

list(s) #['5' , '.' , '6']
s[:2] #'5.'

10.
pass
什麼都不執行,在開發新程序中用來佔位以保證程序完整性。
11.
三元表達式

value = true-expr if condition else false-expr

它和下面這種格式效果一致:

if condition
value = true-expr
else:
value = false-expr

12.
元組構成的元組:

nested_tup = (4,5,6),(1,2) #nested_tup : ((4,5,6),(1,2))

tuple可將任何序列或迭代器轉換爲元組

tuple([4,2,0]) #(4,2,0)
tup = tuple('string') #tup : ('s','t','r','i','n','g')
tup[0] # 's'

元組元素不可修改,但可以添加:

tup = tuple(['foo',[1,2],True])
tup[2] = False #TypeError
tup[1].append(3) #tup : ('foo',[1,2,3],True)

元組拆包:

tup = 4,5,(6,7)
a,b,(c,d) = tup # d : 7

元組方法:count

a = (1,2,3,2)
a.count(2) # 2

13.
列表
可通過方括號[]或者list函數定義:

a_list = [2,3,7,None]
tup = ('1','2','3')
b_list = list(tup) # b_list : ['1','2','3']
b_list[1] = '4' #b_list : ['1','4','3']

14.

b_list.append('dearf')   # b_list : ['1','4','3','dearf']
b_list.insert(1,'dearf') # b_list : ['1','dearf','4','3','dearf']
b_list.remove('dearf')   # b_list : ['1','4','3','dearf']
'3' in b_list        # True
b_list.extend(7,8,(2,3)) # b_liist : ['1','4','3','dearf',7,8,(2,3)]

在相同效果下extend比“+”的操作要快得多
15.
sort

a = [7,2,1,4]
a.sort() # a : [1,2,4,7]
b = a.sorted() # b : [1,2,4,7] a不變
sorted('hourse race') #[' ','a','c','e','h','o','r','r','s']
c = ['mmm','m','mm']
c.sort(key = len) # c : ['m','mm','mmm']
a.sort(reverse = True) # a : [7,4,2,1]

16.
dict
在機器學習這種需要處理文本的情況下,字典的重要性相當大。字典本質上是一個二元元組集。

empty_dict = {}
dict = {'a':'some value' , 'b':[1,2,3,4]}
dict[7] = 'an integer' #dict : {7:'an integer' , 'a':'some value' , 'b':[1,2,3,4]}
'b' in dict #True
del dict[7] #刪除dict中7:'an integer'
ret = dict.pop('a') #刪除dict中'a':'some value'並將此值賦給ret

17.
列表推導式
相當簡潔的過濾一個列表(字典、集合)

strings = ['a','as','bat','car','dove']
[x.upper() for x in strings if len(x)>2] #['BAT','CAR','DOVE']

18.
函數
和C不同,Python的函數可以返回多個值甚至字典:

def f():
    a=5
    b=6
    return{'a':a ,'b':b}

函數亦爲對象
對一個字符串進行數據清洗:
states=[’ Alabama ‘,’Geogria!’,’ Geor’,’south car##’,’West s?’]
方法1:

import re
def clean_strings(strings):
    result = []
    for value in strings:
        value = value.strip()
        value = value.sub('[!#?]',' ',value)#移除標點符號
        value = value.title()
        result.append(value)
    return result

方法2:將作用在字符串上的一系列操作做成列表

def remove_punctution(value)
    return re.sub('[!#?]',' ',value)
clean_ops = [str.strip ,remvoe_punctution , str,title]
def clean_strings(strings ,ops):
    result = []
    for value in strings:
        for function in ops:
            value = function(value)
            result.append(value)
    return result

19.
lambda(匿名)函數

def apply_to_list(some_list ,f)
    return [f(x) for x in some_list]
ints = [4,0,5,6]
apply_to_list(ints ,lambda x:x*2)

20.
生成器
直到迭代完成後再一起輸出每一次迭代的值,xrange生成的就是一個生成器(range生成的是一個列表對象)

gen = (x ** 2 for x in xrange(100)) #這是一種生成器表達方式

功能和下面這個冗長的生成器等價:

def _make_gen()
    for x in xrange(100):
        yield x**2
        gen = _make_gen()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章