Python & Numpy 教程(上)
原英文教程网址:http://cs231n.github.io/python-numpy-tutorial/
------------------------------------------------------------------------------------------------
该教程来自于 Justin Johnson
我们将会使用Python编程语言来完成本课程(斯坦福大学cs231n)的所有作业。Python是一个伟大的通用编程语言,在一些流行库(numpy,scipy,matplotlib)的帮助下,它可以提供一个科学计算的强大环境。
我们希望你们之中的大多数人已经有了使用Python和numpy的经验;其余的人,这个部分将作为一个速成课程,帮助你们掌握Python编程语言,并且使用Python来做科学计算。
也许有些人有过matlab的使用经验,所以我们也推荐numpyfor matlab user。
你还可以找到 IPythonnotebook version of this tutorial here。
Python
Python是一个高级、动态类型多范性编程语言。Python与伪代码很相似,它允许你使用非常少的代码来表达强大的思想。举个例子,下面是一个经典的快速排序算法的Python实现:
def quicksort(arr): if len(arr) <= 1: return arr pivot = arr[len(arr) / 2] left = [x for x in arr if x < pivot] middle = [x for x in arr if x == pivot] right = [x for x in arr if x > pivot] return quicksort(left) + middle + quicksort(right) print quicksort([3,6,8,10,1,2,1]) # Prints "[1, 1, 2, 3, 6, 8, 10]"
Python版本
目前有两种不同的Python支持版本——Python 2.7和Python 3.4。Python 3.0引入了很多向后不兼容的变化,所以使用2.7编写的代码在3.4下可能无法正常工作,反之亦然。这门课程使用的是Python 2.7。
你可以通过在命令行运行 python --version 来查看Python版本。
Basic data types
与其他语言类似,Python有很多基本的数据类型,包括整型、浮点型、布尔型、字符串型。这些类型的表现与在其他编程语言中类似。
Numbers:整数和浮点数与其他语言中类似:
x = 3 print type(x) # Prints "<type 'int'>" print x # Prints "3" print x + 1 # Addition; prints "4" print x - 1 # Subtraction; prints "2" print x * 2 # Multiplication; prints "6" print x ** 2 # Exponentiation; prints "9" x += 1 print x # Prints "4" x *= 2 print x # Prints "8" y = 2.5 print type(y) # Prints "<type 'float'>" print y, y + 1, y * 2, y ** 2 # Prints "2.5 3.5 5.0 6.25"
与许多其他语言不同的是,Python没有一元增加(x++)和减少(x--)操作。
Python也有内置的长整型和复杂数类型,你可以在相关文档中找到。
Booleans:Python实现所有的布尔逻辑通用操作,但是它不使用符号(&&,II,etc),而是使用英文单词:
t = True f = False print type(t) # Prints "<type 'bool'>" print t and f # Logical AND; prints "False" print t or f # Logical OR; prints "True" print not t # Logical NOT; prints "False" print t != f # Logical XOR; prints "True"
Strings:Python对字符串支持很好:
hello = 'hello' # String literals can use single quotes world = "world" # or double quotes; it does not matter. print hello # Prints "hello" print len(hello) # String length; prints "5" hw = hello + ' ' + world # String concatenation print hw # prints "hello world" hw12 = '%s %s %d' % (hello, world, 12) # sprintf style string formatting print hw12 # prints "hello world 12"
字符串对象有很多有用的方法;例如:
s = "hello" print s.capitalize() # Capitalize a string; prints "Hello" print s.upper() # Convert a string to uppercase; prints "HELLO" print s.rjust(7) # Right-justify a string, padding with spaces; prints " hello" print s.center(7) # Center a string, padding with spaces; prints " hello " print s.replace('l', '(ell)') # Replace all instances of one substring with another; # prints "he(ell)(ell)o" print ' world '.strip() # Strip leading and trailing whitespace; prints "world"
你可以在相关文档中找到string方法的列表。
Containers
Python包含一些内置的容器类型:lists(列表),dictionaries(字典), sets(集合), and tuples(元组)。
Lists
list是数组在Python中的等价物,但是它是可变大小的,且可以包含不同类型的元素:
xs = [3, 1, 2] # Create a list print xs, xs[2] # Prints "[3, 1, 2] 2" print xs[-1] # Negative indices count from the end of the list; prints "2" xs[2] = 'foo' # Lists can contain elements of different types print xs # Prints "[3, 1, 'foo']" xs.append('bar') # Add a new element to the end of the list print xs # Prints "[3, 1, 'foo', 'bar']" x = xs.pop() # Remove and return the last element of the list print x, xs # Prints "bar [3, 1, 'foo']"
实际上,你可以在官网文档中找到更多的关于lists的细节。
Slicing:除了可以每次访问列表的一个元素,Python提供了简洁的语法来访问子列表;这就叫做slicing:
nums = range(5) # range is a built-in function that creates a list of integers print nums # Prints "[0, 1, 2, 3, 4]" print nums[2:4] # Get a slice from index 2 to 4 (exclusive); prints "[2, 3]" print nums[2:] # Get a slice from index 2 to the end; prints "[2, 3, 4]" print nums[:2] # Get a slice from the start to index 2 (exclusive); prints "[0, 1]" print nums[:] # Get a slice of the whole list; prints ["0, 1, 2, 3, 4]" print nums[:-1] # Slice indices can be negative; prints ["0, 1, 2, 3]" nums[2:4] = [8, 9] # Assign a new sublist to a slice print nums # Prints "[0, 1, 8, 9, 4]"
我们还会在numpy arrays上下文中看到slicing。
Loops:你可以像这样循环遍历列表中的元素:
animals = ['cat', 'dog', 'monkey'] for animal in animals: print animal # Prints "cat", "dog","monkey", each on its own line.
如果你想在循环体中访问每个元素的索引,可使用内置的 enumerate 函数:
animals = ['cat', 'dog', 'monkey'] for idx, animal in enumerate(animals): print '#%d: %s' % (idx + 1, animal) # Prints "#1: cat", "#2: dog", "#3: monkey", each on its own line
List comprehensions:编程的时候,经常会涉及到把数据从一个类型转换到另一个类型。举个简单的例子,考虑下面计算平方数的代码:
nums = [0, 1, 2, 3, 4] squares = [] for x in nums: squares.append(x ** 2) print squares # Prints [0, 1, 4, 9, 16]
list comprehensions 也可以包含条件:
nums = [0, 1, 2, 3, 4] even_squares = [x ** 2 for x in nums if x %2 == 0] print even_squares # Prints "[0, 4, 16]"
Dictionaries
一个字典存储了(key,value)对,这与Java中的Map或者Javascript中的object都很相似。你可以这样使用字典:
d = {'cat': 'cute', 'dog': 'furry'} # Create a new dictionary with some data print d['cat'] # Get an entry from a dictionary; prints "cute" print 'cat' in d # Check if a dictionary has a given key; prints "True" d['fish'] = 'wet' # Set an entry in a dictionary print d['fish'] # Prints "wet" # print d['monkey'] # KeyError: 'monkey' not a key of d print d.get('monkey', 'N/A') # Get an element with a default; prints "N/A" print d.get('fish', 'N/A') # Get an element with a default; prints "wet" del d['fish'] # Remove an element from a dictionary print d.get('fish', 'N/A') # "fish" is no longer a key; prints "N/A"
在官方文档中可以找到所有关于字典的知识。
Loops:很容易对字典中的keys进行迭代:
d = {'person': 2, 'cat': 4, 'spider': 8} for animal in d: legs = d[animal] print 'A %s has %d legs' % (animal, legs) # Prints "A person has 2 legs", "A spider has 8 legs", "A cat has 4 legs"
如果想要访问keys和对应的values,可以使用iteritems 方法:
d = {'person': 2, 'cat': 4, 'spider': 8} for animal, legs in d.iteritems(): print 'A %s has %d legs' % (animal, legs) # Prints "A person has 2 legs", "A spider has 8 legs", "A cat has 4 legs"
Dictionary comprehensions:这与list comprehensions是相似的,但是允许你方便地构建字典。例如:
nums = [0, 1, 2, 3, 4] even_num_to_square = {x: x ** 2 for x in nums if x % 2 == 0} print even_num_to_square # Prints "{0: 0, 2: 4, 4: 16}"
Sets
Set是不同元素的无序集合。下面是一个简单的例子:
animals = {'cat', 'dog'} print 'cat' in animals # Check if an element is in a set; prints "True" print 'fish' in animals # prints "False" animals.add('fish') # Add an element to a set print 'fish' in animals # Prints "True" print len(animals) # Number of elements in a set; prints "3" animals.add('cat') # Adding an element that is already in the set does nothing print len(animals) # Prints "3" animals.remove('cat') # Remove an element from a set print len(animals) # Prints "2"
通常,你想要知道的所有关于sets的东西可以在官方文档中找到。
animals = {'cat', 'dog', 'fish'} for idx, animal in enumerate(animals): print '#%d: %s' % (idx + 1, animal) # Prints "#1: fish", "#2: dog", "#3: cat"
Set comprehensions:与dictionaries和lists类似,我们可以很容易地使用set comprehensions来构建sets:
from math import sqrt nums = {int(sqrt(x)) for x in range(30)} print nums # Prints "set([0, 1, 2, 3, 4, 5])"
Tuples
一个tuple是一个(不可改变)有序值列表。Tuple在很多方面和list相似;最大的不同是tuples可以被用作字典的keys和sets的元素,但是lists却不能。这里是一个简单的例子:
d = {(x, x + 1): x for x in range(10)} # Create a dictionary with tuple keys t = (5, 6) # Create a tuple print type(t) # Prints "<type 'tuple'>" print d[t] # Prints "5" print d[(1, 2)] # Prints "1"
官方文档中有更多的关于tuple的例子。
Functions
Python函数使用def关键字来定义。例如:
def sign(x): if x > 0: return 'positive' elif x < 0: return 'negative' else: return 'zero' for x in [-1, 0, 1]: print sign(x) # Prints "negative", "zero", "positive"
我们经常会将函数定义为可选参数的,像这样:
def hello(name, loud=False): if loud: print 'HELLO, %s!' % name.upper() else: print 'Hello, %s' % name hello('Bob') # Prints "Hello, Bob" hello('Fred', loud=True) # Prints "HELLO, FRED!"
更多的关于Python函数的内容请参考官方文档。
Classes
Python中定义类的语法是简洁明了的:
class Greeter(object): # Constructor def __init__(self, name): self.name = name # Create an instance variable # Instance method def greet(self, loud=False): if loud: print 'HELLO, %s!' % self.name.upper() else: print 'Hello, %s' % self.name g = Greeter('Fred') # Construct an instance of the Greeter class g.greet() # Call an instance method; prints "Hello, Fred" g.greet(loud=True) # Call an instance method; prints "HELLO, FRED!"
同样可以在官方文档中找到更多的内容。
======================================
关于Numpy和其他库的使用将会在下一篇中介绍。