1def sign(x):
2 if x > 0:
3 return 'positive'
4 elif x < 0:
5 return 'negative'
6 else:
7 return 'zero'
8for x in [-1, 0, 1]:
9 print sign(x)
10# Prints "negative", "zero", "positive"
我们常常使用可选参数来定义函数:
1def hello(name, loud=False):
2 if loud:
3 print 'HELLO, %s' % name.upper()
4 else:
5 print 'Hello, %s!' % name
6hello('Bob') # Prints "Hello, Bob"
7hello('Fred', loud=True) # Prints "HELLO, FRED!"
函数还有很多内
容,可以查看文档。
类Classes
Python对于类的定义是简单直接的: 1class Greeter(object):
2 # Constructor
3 def __init__(self, name):
4 self.name = name # Create an instance variable
5 # Instance method
6 def greet(self, loud=False):
7 if loud:
8 print 'HELLO, %s!' % self.name.upper()
9 else:
10 print 'Hello, %s' % self.name
11g = Greeter('Fred') # Construct an instance of the Greeter class
12g.greet() # Call an instance method; prints "Hello, Fred"
13g.greet(loud=True) # Call an instance method; prints "HELLO, FRED!"
更多类的信息请查阅文档。
Numpy
Numpy是Python中用于科学计算的核心库。它提供了高性能的多维数组对象,以及相关工具。
数组Arrays
一个numpy数组是一个由不同数值组成的网格。网格中的数据都是同一种数据类型,可以通过非负整型数的元组来访问。维度的数量被称为数组的阶,数组的大小是一个由整型数构成的元组,可以描述数组不同维度上的大小。
我们可以从列表创建数组,然后利用方括号访问其中的元素:
1import numpy as np
2a = np.array([1, 2, 3]) # Create a rank 1 array
3print type(a) # Prints ""
4print a.shape # Prints "(3,)"
5print a[0], a[1], a[2] # Prints "1 2 3"
6a[0] = 5 # Change an element of the array
7print a # Prints "[5, 2, 3]"
8b = np.array([[1,2,3],[4,5,6]]) # Create a rank 2 array
9print b # 显示一下矩阵b
10print b.shape # Prints "(2, 3)"
11print b[0, 0], b[0, 1], b[1, 0] # Prints "1 2 4"
Numpy还提供了很多其他创建数组的方法: 1import numpy as np
2a = np.zeros((2,2)) # Create an array of all zeros
3print a # Prints "[[ 0. 0.]
4 # [ 0. 0.]]"
5b = np.ones((1,2)) # Create an array of all ones
6print b # Prints "[[ 1. 1.]]"
7c = np.full((2,2), 7) # Create a constant array
8print c # Prints "[[ 7. 7.]
9 # [ 7. 7.]]"
10d = np.eye(2) # Create a 2x2 identity matrix
11print d # Prints "[[ 1. 0.]
12 # [ 0. 1.]]"
13e = np.random.random((2,2)) # Create an array filled with random values
14print e # Might print "[[ 0.91940167 0.08143941]
15 # [ 0.68744134 0.87236687]]"
其他数组相关方法,请查看文档。
访问数组
Numpy提供了多种访问数组的方法。
切片:和Python列表类似,numpy数组可以使用切片语法。因为数组可以是多维的,所以你必须为每个维度指定好切片。
1import numpy as np
2# Create the following rank 2 array with shape (3, 4)
3# [[ 1 2 3 4]
4# [ 5 6 7 8]
5# [ 9 10 11 12]]
6a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
7# Use slicing to pull out the subarray consisting of the first 2 rows
8# and columns 1 and 2; b is the following array of shape (2, 2):
9# [[2 3]
10# [6 7]]
11b = a[:2, 1:3]
12# A slice of an array is a view into the same data, so modifying it
13# will modify the original array.
14print a[0, 1] # Prints "2"
15b[0, 0] = 77 # b[0, 0] is the same piece of data as a[0, 1]
16print a[0, 1] # Prints "77"
你可以同时使用整型和切片语法来访问数组。但是,这样做会产生一个比原数组低阶的新数组。需要注意的是,这里和MATLAB中的情况是不同的:
1import numpy as np
2# Create the following rank 2 array with shape (3, 4)
3# [[ 1 2 3 4]
4# [ 5 6 7 8]
5# [ 9 10 11 12]]
6a = np.array([[1,2,3,4], [5