Python语法速览与机器学习开发环境搭建

开发 开发工具
Python 是一门高阶、动态类型的多范式编程语言。人生苦短,请用Python,大量功能强大的语法糖的同时让很多时候Python代码看上去有点像伪代码。

Python

Python 是一门高阶、动态类型的多范式编程语言。人生苦短,请用Python,大量功能强大的语法糖的同时让很多时候Python代码看上去有点像伪代码。譬如我们用Python实现的简易的快排相较于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社区存在的最大的问题就是版本分裂,这也是笔者一直觉得有点鸡肋般的感觉,毕竟对于处女座而言实在是难受。目前Python社区中存在两个不同的主要版本:2.7与3.4。Python 3.0引入了很多不向后兼容的变化,因此很多遵循2.7版本的代码并不能适用于3.4版本。我们可以使用python --version命令来查看当前使用的版本。

常用习惯

模块 注意点 换行 反斜杠()继续上一行,Python文件以模块形式组织。Python程序语句不以分号结尾,而以换行符结尾。Python 使用硬回车来分割语句, 冒号和缩进来分割代码块。C++ 和 Java 使用分号来分割语句, 花括号来分割代码块。 注释 a. 使用#符号标示注释; b. 在模块、类或者函数起始添加一个字符串起文档作用; c. 使用三引号标示注释。 print """ Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to """ 主流程 Python 中没有子程序,只有函数, 所有的函数都有返回值,并且所有的函数都以 def 开始。 字符串 Python中单引号与双引号的区别类似于PHP中,双引号中可以包括单引号。 数组 Python中数组下标可以为负数,即从右端开始计量,-1即为最后一个数。Python不可以修改数组中值,字符串下标索引方式类似于MATLAB。 函数 Python的函数可以嵌套定义

Installation:环境搭建

Conda

笔者推荐使用Anaconda作为环境搭建工具,并且推荐使用Python 3.5版本,可以在这里下载。如果是习惯使用Docker的小伙伴可以参考anaconda-notebook

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

安装完毕之后可以使用如下命令验证安装是否完毕:

  1. conda --version 

安装完毕之后我们就可以创建具体的开发环境了,主要是通过create命令来创建新的独立环境:

  1. conda create --name snowflakes biopython 

该命令会创建一个名为snowflakes并且安装了Biopython的环境,如果你需要切换到该开发环境,可以使用activate命令:

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

我们也可以在创建环境的时候指明是用python2还是python3:

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

环境创建完毕之后,我们可以使用info命令查看所有环境:

  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 

当我们切换到某个具体的环境后,可以安装依赖包了:

  1. conda list # 列举当前环境中的所有依赖包  
  2. conda install nltk # 安装某个新的依赖 

Jupyter Notebook

在Conda安装之后,Jupyter Notebook是默认安装好的,直接在工作目录下打开即可:

jupyter notebook

基础数据类型

和其他主流语言一样,Python为我们提供了包括integer、float、boolean、strings等在内的很多基础类型。

数值类型

  1. x = 3 
  2. print type(x) # Prints "<type 'int'>" 
  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 "<type 'float'>" 
  14. print y, y + 1, y * 2, y ** 2 # Prints "2.5 3.5 5.0 6.25" 

不过需要注意的是,Python并没有x++或者x--这样的自增或者自减操作符。另外,Python内置的也提供了长整型与其他复杂数值类型的整合,可以参考这里。

布尔类型

Python提供了常见的逻辑操作符,不过需要注意的是Python中并没有使用&&、||等,而是直接使用了英文单词。

  1. t = True 
  2. f = False 
  3. print type(t) # Prints "<type 'bool'>" 
  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" 

可以在这里中查看详细的方法列表。

复杂数据类型

列表

Python中的列表等价于数组,不过其能够动态扩展并且能够存放不同类型的数值。

  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']" 

同样你可以在文档中查看更多的细节。

切片

Python中对于数组的访问也相当人性化,通过简单的操作符即可以完成对于数组中子数组的截取。

  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循环来遍历数组中的元素,就像下面介个样纸:

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

如果你在循环的同时也希望能够获取到当前元素下标,可以使用enumerate函数:

  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 

变换

在编程中我们经常需要对数组进行变换,比较著名的我们可以使用map、reduce、filter这几个函数,而在Python中提供了非常方便的List Comprehension操作符。譬如我们需要对数组中元素进行依次平方操作

  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" 

如果你希望同时访问键和其对应的值,可以使用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" 

遍历

集合遍历的语法和数组遍历很类似,不过因为集合本身是无序的,因此你不能够依赖于遍历的顺序来预测集合中元素的顺序:

  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很类似于列表,不过区别在于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 "<type 'tuple'>" 
  4. print d[t]       # Prints "5" 
  5. print d[(1, 2)]  # Prints "1" 

Function:函数

Python中的函数使用def关键字进行定义,譬如:

  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中的函数还支持可选参数:

  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!" 

 【本文是51CTO专栏作者“张梓雄 ”的原创文章,如需转载请通过51CTO与作者联系】

戳这里,看该作者更多好文

责任编辑:武晓燕 来源: 51CTO专栏
相关推荐

2017-11-23 15:24:35

Python速览实战

2018-04-09 14:26:06

Go语法实践

2017-04-17 15:03:16

Python自然语言处理

2011-07-22 18:13:59

IOS IDE Xcode

2021-04-25 08:06:42

人工智能AI机器人

2012-04-28 08:43:12

CentOS

2018-04-09 10:16:27

机器学习深度学习AI

2011-06-03 14:36:32

IOS 环境搭建

2011-06-03 15:36:22

IOS 环境搭建

2009-09-07 18:14:55

Scala开发环境

2011-06-03 16:05:20

IOS 环境搭建

2011-06-03 15:08:09

IOS 环境搭建

2017-04-25 17:29:24

2010-03-04 11:01:06

Python开发环境

2010-02-03 14:37:10

Python 开发环境

2020-10-12 11:33:00

鸿蒙

2023-11-18 19:28:20

Android 14

2013-11-22 16:45:28

SASJMP11

2018-07-19 10:35:12

机器学习数据平台

2013-07-23 06:11:44

Android开发学习Android开发环境Java
点赞
收藏

51CTO技术栈公众号