python学习笔记
Basic Grammar
Basic data types
- X unary increment (
x++) or decrement (x--) operators. andinstead of&&,orinstead of||,notinstead of!and!=forXOR
String
length -
len(str)formatting -
'%s %s %d' % (str1, str2, 1)capitalize -
str.capitalize()uppercase -
str.upper()Right-justify (右对齐) -
str.rjust(totallength)totallength = len(str) + space in left
Center(居中) -
str.center(totallength)Replace -
str.replace(str1, str2), allstr1instrwill be replaced bystr2Strip leading and trailing whitespace -
str.strip()
Containers
Lists
- Negative index count from the end -
list[-1] - can contain elements of different types
- add new ele -
list.append(newEle) - remove and return the last ele -
list.pop()
Slicing
- get sublist from index
xto indexy- nums[x:y]- no
x: from the start - no
y: to the end xandycan be negative
- no
Loops
- get elements in the list -
for item in list - get both indices and elements in the list -
for index, item in list
List comprehensions
transform a list of elements to another:
newList = [(do something to item) for item in oldList]With conditions:
newList = [(do something to item) for item in oldList if (in some condition)]
Dictionaries
- key-value set
- access with a default value -
dic.get(key, defaultValue) - delete -
del d[key]
Loops
- get keys in the list -
for key in dic - get both keys and value in the list -
for key, value in dic.items()
Dictionary comprehensions
- same with list, and change the value part of the dictionary
- use
{}, X[]
Sets
an unordered collection of distinct elements
judge whether an element is in the set -
ele in setaddremovelen
Loops
- when access both indices and elements, the order is not as assumptions
Set comprehensions
- same, use
{}
Tuples
- ordered list of values
- similar to list, but tuples can be used as keys in dictionaries and as element of sets
Functions
- ```
def functionName(para1, para2, …):1
2
3
4
5
6
7
8
9
10
### Classes
- ```python
class className():
# constructor
def __init__(self, para1, para2, ...):
# do sth
# methods, definition of functions
Numpy
Arrays
all elements are of the same type
indexed by a tuple of nonnegative integers
rank - number of dimensions of the array
shape - a tuple of integers giving the size of the array along each dimension
initialize -
1
2
3np.array([1,2,3])
np.array([[1,2,3],[4,5,6]])
# more ranks- all zeros -
np.zeros(shape) - all ones -
np.ones(shape) - all specific number -
np.ones(shape, specificNumber) - idenity matrix -
np.eye(dimension)- the shape of this matrix is
dimension * dimension
- the shape of this matrix is
- all zeros -
Array indexing
Slicing
- slice indexing - specify the range for each dimension -
array[range in the first dimension, range in the second dimention, ...]
Accessing elements
- integer indexing -
array[index in the first dimension, index in the second dimension]
mix of slicing by index and range
- if use only slice indexing, the returning array will be of the same rank
1 | import numpy as np |
if use integer indexing, arbitrary arrays can be construct.
a[[0,1,2]] => index 0, 1 and 2 in first dimension
Select one element from each row of a using the indices in b(an array of indices,
[0, 2, 0, 1])1
a[np.arange(4), b]
The output is a[0, 0], a[1, 2], a[2, 0], a[2, 1].
Boolean array indexing
1 | a = np.array([[1,2], [3, 4], [5, 6]]) |
Datatypes
1 | np.array(ARRAYDATA, dtype=ARRAYTYPE) |
*and/is elementwisematrix multiplication or vector multiplication -
dotAs a function:
np.dot(x, y)As an instance method:
x.dot(y)Transpose -
v.T`
SciPy
Image operations
read from file into a numpy arrays -
imread(FILEPATH)Computing distances between sets of points -
scipy.spatial.distance.pdist
Matplotlib
plot,subplotandimshow