日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
Python語法速覽與機器學(xué)習(xí)開發(fā)環(huán)境搭建

Python

創(chuàng)新互聯(lián)專注為客戶提供全方位的互聯(lián)網(wǎng)綜合服務(wù),包含不限于做網(wǎng)站、網(wǎng)站建設(shè)、忻州網(wǎng)絡(luò)推廣、微信平臺小程序開發(fā)、忻州網(wǎng)絡(luò)營銷、忻州企業(yè)策劃、忻州品牌公關(guān)、搜索引擎seo、人物專訪、企業(yè)宣傳片、企業(yè)代運營等,從售前售中售后,我們都將竭誠為您服務(wù),您的肯定,是我們最大的嘉獎;創(chuàng)新互聯(lián)為所有大學(xué)生創(chuàng)業(yè)者提供忻州建站搭建服務(wù),24小時服務(wù)熱線:18980820575,官方網(wǎng)址:www.cdcxhl.com

Python 是一門高階、動態(tài)類型的多范式編程語言。人生苦短,請用Python,大量功能強大的語法糖的同時讓很多時候Python代碼看上去有點像偽代碼。譬如我們用Python實現(xiàn)的簡易的快排相較于Java會顯得很短小精悍:

 
 
 
 
  1. def quicksort(arr): 
  2.     if len(arr) <= 1: 
  3.         return arr 
  4.     pivot = arr[len(arr) / 2] 
  5.     left = [x for x in arr if x < pivot] 
  6.     middle = [x for x in arr if x == pivot] 
  7.     right = [x for x in arr if x > pivot] 
  8.     return quicksort(left) + middle + quicksort(right) 
  9.      
  10. print quicksort([3,6,8,10,1,2,1]) 
  11. # Prints "[1, 1, 2, 3, 6, 8, 10]" 

Python 版本

Python社區(qū)存在的最大的問題就是版本分裂,這也是筆者一直覺得有點雞肋般的感覺,畢竟對于處女座而言實在是難受。目前Python社區(qū)中存在兩個不同的主要版本:2.7與3.4。Python 3.0引入了很多不向后兼容的變化,因此很多遵循2.7版本的代碼并不能適用于3.4版本。我們可以使用python --version命令來查看當(dāng)前使用的版本。

常用習(xí)慣

模塊 注意點 換行 反斜杠()繼續(xù)上一行,Python文件以模塊形式組織。Python程序語句不以分號結(jié)尾,而以換行符結(jié)尾。Python 使用硬回車來分割語句, 冒號和縮進來分割代碼塊。C++ 和 Java 使用分號來分割語句, 花括號來分割代碼塊。 注釋 a. 使用#符號標(biāo)示注釋; b. 在模塊、類或者函數(shù)起始添加一個字符串起文檔作用; c. 使用三引號標(biāo)示注釋。 print """ Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to """ 主流程 Python 中沒有子程序,只有函數(shù), 所有的函數(shù)都有返回值,并且所有的函數(shù)都以 def 開始。 字符串 Python中單引號與雙引號的區(qū)別類似于PHP中,雙引號中可以包括單引號。 數(shù)組 Python中數(shù)組下標(biāo)可以為負(fù)數(shù),即從右端開始計量,-1即為最后一個數(shù)。Python不可以修改數(shù)組中值,字符串下標(biāo)索引方式類似于MATLAB。 函數(shù) Python的函數(shù)可以嵌套定義

Installation:環(huán)境搭建

Conda

筆者推薦使用Anaconda作為環(huán)境搭建工具,并且推薦使用Python 3.5版本,可以在這里下載。如果是習(xí)慣使用Docker的小伙伴可以參考anaconda-notebook

 
 
 
 
  1. docker pull rothnic/anaconda-notebook 
  2. docker run -p 8888:8888 -i -t rothnic/anaconda-notebook 

安裝完畢之后可以使用如下命令驗證安裝是否完畢:

 
 
 
 
  1. conda --version 

安裝完畢之后我們就可以創(chuàng)建具體的開發(fā)環(huán)境了,主要是通過create命令來創(chuàng)建新的獨立環(huán)境:

 
 
 
 
  1. conda create --name snowflakes biopython 

該命令會創(chuàng)建一個名為snowflakes并且安裝了Biopython的環(huán)境,如果你需要切換到該開發(fā)環(huán)境,可以使用activate命令:

  • Linux, OS X: source activate snowflakes
  • Windows: activate snowflakes

我們也可以在創(chuàng)建環(huán)境的時候指明是用python2還是python3:

 
 
 
 
  1. conda create --name bunnies python=3 astroid babel 

環(huán)境創(chuàng)建完畢之后,我們可以使用info命令查看所有環(huán)境:

 
 
 
 
  1. conda info --envs 
  2. conda environments: 
  3.  
  4.      snowflakes          * /home/username/miniconda/envs/snowflakes 
  5.      bunnies               /home/username/miniconda/envs/bunnies 
  6.      root                  /home/username/miniconda 

當(dāng)我們切換到某個具體的環(huán)境后,可以安裝依賴包了:

 
 
 
 
  1. conda list # 列舉當(dāng)前環(huán)境中的所有依賴包  
  2. conda install nltk # 安裝某個新的依賴 

Jupyter Notebook

在Conda安裝之后,Jupyter Notebook是默認(rèn)安裝好的,直接在工作目錄下打開即可:

jupyter notebook

基礎(chǔ)數(shù)據(jù)類型

和其他主流語言一樣,Python為我們提供了包括integer、float、boolean、strings等在內(nèi)的很多基礎(chǔ)類型。

數(shù)值類型

 
 
 
 
  1. x = 3 
  2. print type(x) # Prints "
  3. print x       # Prints "3" 
  4. print x + 1   # Addition; prints "4" 
  5. print x - 1   # Subtraction; prints "2" 
  6. print x * 2   # Multiplication; prints "6" 
  7. print x ** 2  # Exponentiation; prints "9" 
  8. x += 1 
  9. print x  # Prints "4" 
  10. x *= 2 
  11. print x  # Prints "8" 
  12. y = 2.5 
  13. print type(y) # Prints "
  14. print y, y + 1, y * 2, y ** 2 # Prints "2.5 3.5 5.0 6.25" 

不過需要注意的是,Python并沒有x++或者x--這樣的自增或者自減操作符。另外,Python內(nèi)置的也提供了長整型與其他復(fù)雜數(shù)值類型的整合,可以參考這里。

布爾類型

Python提供了常見的邏輯操作符,不過需要注意的是Python中并沒有使用&&、||等,而是直接使用了英文單詞。

 
 
 
 
  1. t = True 
  2. f = False 
  3. print type(t) # Prints "
  4. print t and f # Logical AND; prints "False" 
  5. print t or f  # Logical OR; prints "True" 
  6. print not t   # Logical NOT; prints "False" 
  7. print t != f  # Logical XOR; prints "True"  

字符串

Python對于字符串的支持還是很好的,不過需要注意到utf-8編碼問題。

 
 
 
 
  1. hello = 'hello'   # String literals can use single quotes 
  2. world = "world"   # or double quotes; it does not matter. 
  3. print hello       # Prints "hello" 
  4. print len(hello)  # String length; prints "5" 
  5. hw = hello + ' ' + world  # String concatenation 
  6. print hw  # prints "hello world" 
  7. hw12 = '%s %s %d' % (hello, world, 12)  # sprintf style string formatting 
  8. print hw12  # prints "hello world 12" 

Python中的字符串對象還包含了很多有用的方法,譬如:

 
 
 
 
  1. s = "hello" 
  2. print s.capitalize()  # Capitalize a string; prints "Hello" 
  3. print s.upper()       # Convert a string to uppercase; prints "HELLO" 
  4. print s.rjust(7)      # Right-justify a string, padding with spaces; prints "  hello" 
  5. print s.center(7)     # Center a string, padding with spaces; prints " hello " 
  6. print s.replace('l', '(ell)')  # Replace all instances of one substring with another; 
  7.                                # prints "he(ell)(ell)o" 
  8. print '  world '.strip()  # Strip leading and trailing whitespace; prints "world" 

可以在這里中查看詳細(xì)的方法列表。

復(fù)雜數(shù)據(jù)類型

列表

Python中的列表等價于數(shù)組,不過其能夠動態(tài)擴展并且能夠存放不同類型的數(shù)值。

 
 
 
 
  1. xs = [3, 1, 2]   # Create a list 
  2. print xs, xs[2]  # Prints "[3, 1, 2] 2" 
  3. print xs[-1]     # Negative indices count from the end of the list; prints "2" 
  4. xs[2] = 'foo'    # Lists can contain elements of different types 
  5. print xs         # Prints "[3, 1, 'foo']" 
  6. xs.append('bar') # Add a new element to the end of the list 
  7. print xs         # Prints "[3, 1, 'foo', 'bar']" 
  8. x = xs.pop()     # Remove and return the last element of the list 
  9. print x, xs      # Prints "bar [3, 1, 'foo']" 

同樣你可以在文檔中查看更多的細(xì)節(jié)。

切片

Python中對于數(shù)組的訪問也相當(dāng)人性化,通過簡單的操作符即可以完成對于數(shù)組中子數(shù)組的截取。

 
 
 
 
  1. nums = range(5)    # range is a built-in function that creates a list of integers 
  2. print nums         # Prints "[0, 1, 2, 3, 4]" 
  3. print nums[2:4]    # Get a slice from index 2 to 4 (exclusive); prints "[2, 3]" 
  4. print nums[2:]     # Get a slice from index 2 to the end; prints "[2, 3, 4]" 
  5. print nums[:2]     # Get a slice from the start to index 2 (exclusive); prints "[0, 1]" 
  6. print nums[:]      # Get a slice of the whole list; prints ["0, 1, 2, 3, 4]" 
  7. print nums[:-1]    # Slice indices can be negative; prints ["0, 1, 2, 3]" 
  8. nums[2:4] = [8, 9] # Assign a new sublist to a slice 
  9. print nums         # Prints "[0, 1, 8, 9, 4]" 

遍歷

你可以使用基本的for循環(huán)來遍歷數(shù)組中的元素,就像下面介個樣紙:

 
 
 
 
  1. animals = ['cat', 'dog', 'monkey'] 
  2. for animal in animals: 
  3.     print animal 
  4. # Prints "cat", "dog", "monkey", each on its own line. 

如果你在循環(huán)的同時也希望能夠獲取到當(dāng)前元素下標(biāo),可以使用enumerate函數(shù):

 
 
 
 
  1. animals = ['cat', 'dog', 'monkey'] 
  2. for idx, animal in enumerate(animals): 
  3.     print '#%d: %s' % (idx + 1, animal) 
  4. # Prints "#1: cat", "#2: dog", "#3: monkey", each on its own line 

變換

在編程中我們經(jīng)常需要對數(shù)組進行變換,比較著名的我們可以使用map、reduce、filter這幾個函數(shù),而在Python中提供了非常方便的List Comprehension操作符。譬如我們需要對數(shù)組中元素進行依次平方操作

 
 
 
 
  1. nums = [0, 1, 2, 3, 4] 
  2. squares = [] 
  3. for x in nums: 
  4.     squares.append(x ** 2) 
  5. print squares   # Prints [0, 1, 4, 9, 16] 

我們可以簡寫為如下方式:

 
 
 
 
  1. nums = [0, 1, 2, 3, 4] 
  2. squares = [x ** 2 for x in nums] 
  3. print squares   # Prints [0, 1, 4, 9, 16] 

List Comprehensions也支持進行條件選擇:

 
 
 
 
  1. nums = [0, 1, 2, 3, 4] 
  2. even_squares = [x ** 2 for x in nums if x % 2 == 0] 
  3. print even_squares  # Prints "[0, 4, 16]" 

字典

Python中的字典類型即類似于Java中的Map或者JavaScript中的Object,也就是所謂的鍵值對類型,基本的使用方式為:

 
 
 
 
  1. d = {'cat': 'cute', 'dog': 'furry'}  # Create a new dictionary with some data 
  2. print d['cat']       # Get an entry from a dictionary; prints "cute" 
  3. print 'cat' in d     # Check if a dictionary has a given key; prints "True" 
  4. d['fish'] = 'wet'    # Set an entry in a dictionary 
  5. print d['fish']      # Prints "wet" 
  6. # print d['monkey']  # KeyError: 'monkey' not a key of d 
  7. print d.get('monkey', 'N/A')  # Get an element with a default; prints "N/A" 
  8. print d.get('fish', 'N/A')    # Get an element with a default; prints "wet" 
  9. del d['fish']        # Remove an element from a dictionary 
  10. print d.get('fish', 'N/A') # "fish" is no longer a key; prints "N/A" 

遍歷

對于字典的遍歷也非常簡單:

 
 
 
 
  1. d = {'person': 2, 'cat': 4, 'spider': 8} 
  2. for animal in d: 
  3.     legs = d[animal] 
  4.     print 'A %s has %d legs' % (animal, legs) 
  5. # Prints "A person has 2 legs", "A spider has 8 legs", "A cat has 4 legs" 

如果你希望同時訪問鍵和其對應(yīng)的值,可以使用iteritems方法:

 
 
 
 
  1. d = {'person': 2, 'cat': 4, 'spider': 8} 
  2. for animal, legs in d.iteritems(): 
  3.     print 'A %s has %d legs' % (animal, legs) 
  4. # Prints "A person has 2 legs", "A spider has 8 legs", "A cat has 4 legs" 

變換

 
 
 
 
  1. nums = [0, 1, 2, 3, 4] 
  2. even_num_to_square = {x: x ** 2 for x in nums if x % 2 == 0} 
  3. print even_num_to_square  # Prints "{0: 0, 2: 4, 4: 16}" 

Set

Set是一系列無序且唯一的元素的集合:

 
 
 
 
  1. animals = {'cat', 'dog'} 
  2. print 'cat' in animals   # Check if an element is in a set; prints "True" 
  3. print 'fish' in animals  # prints "False" 
  4. animals.add('fish')      # Add an element to a set 
  5. print 'fish' in animals  # Prints "True" 
  6. print len(animals)       # Number of elements in a set; prints "3" 
  7. animals.add('cat')       # Adding an element that is already in the set does nothing 
  8. print len(animals)       # Prints "3" 
  9. animals.remove('cat')    # Remove an element from a set 
  10. print len(animals)       # Prints "2" 

遍歷

集合遍歷的語法和數(shù)組遍歷很類似,不過因為集合本身是無序的,因此你不能夠依賴于遍歷的順序來預(yù)測集合中元素的順序:

 
 
 
 
  1. animals = {'cat', 'dog', 'fish'} 
  2. for idx, animal in enumerate(animals): 
  3.     print '#%d: %s' % (idx + 1, animal) 
  4. # Prints "#1: fish", "#2: dog", "#3: cat" 

變換

 
 
 
 
  1. from math import sqrt 
  2. nums = {int(sqrt(x)) for x in range(30)} 
  3. print nums  # Prints "set([0, 1, 2, 3, 4, 5])" 

Tuples

Python中的Tuple指不可變的有序元素集合,Tuple很類似于列表,不過區(qū)別在于Tuple可以做字典中的鍵類型,而列表則不可以。

 
 
 
 
  1. d = {(x, x + 1): x for x in range(10)}  # Create a dictionary with tuple keys 
  2. t = (5, 6)       # Create a tuple 
  3. print type(t)    # Prints "
  4. print d[t]       # Prints "5" 
  5. print d[(1, 2)]  # Prints "1" 

Function:函數(shù)

Python中的函數(shù)使用def關(guān)鍵字進行定義,譬如:

 
 
 
 
  1. def sign(x): 
  2.     if x > 0: 
  3.         return 'positive' 
  4.     elif x < 0: 
  5.         return 'negative' 
  6.     else: 
  7.         return 'zero' 
  8.  
  9. for x in [-1, 0, 1]: 
  10.     print sign(x) 
  11. # Prints "negative", "zero", "positive" 

同時,Python中的函數(shù)還支持可選參數(shù):

 
 
 
 
  1. def hello(name, loud=False): 
  2.     if loud: 
  3.         print 'HELLO, %s!' % name.upper() 
  4.     else: 
  5.         print 'Hello, %s' % name 
  6.  
  7. hello('Bob') # Prints "Hello, Bob" 
  8. hello('Fred', loud=True)  # Prints "HELLO, FRED!" 

Classes:類

Python中對于類的定義也很直接:

 
 
 
 
  1. class Greeter(object): 
  2.      
  3.     # Constructor 
  4.     def __init__(self, name): 
  5.         self.name = name  # Create an instance variable 
  6.          
  7.     # Instance method 
  8.     def greet(self, loud=False): 
  9.         if loud: 
  10.             print 'HELLO, %s!' % self.name.upper() 
  11.         else: 
  12.             print 'Hello, %s' % self.name 
  13.          
  14. g = Greeter('Fred')  # Construct an instance of the Greeter class 
  15. g.greet()            # Call an instance method; prints "Hello, Fred" 
  16. g.greet(loud=True)   # Call an instance method; prints "HELLO, FRED!" 

 【本文是專欄作者“張梓雄 ”的原創(chuàng)文章,如需轉(zhuǎn)載請通過與作者聯(lián)系】

戳這里,看該作者更多好文


當(dāng)前文章:Python語法速覽與機器學(xué)習(xí)開發(fā)環(huán)境搭建
網(wǎng)頁地址:http://www.5511xx.com/article/cdogshe.html