python学习笔记

reference: http://cs231n.github.io/python-numpy-tutorial/

Basic Grammar

Basic data types

  • X unary increment (x++) or decrement (x--) operators.
  • and instead of &&, or instead of ||, not instead of ! and != for XOR

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), all str1 in str will be replaced by str2

  • Strip 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 x to index y - nums[x:y]
    • no x: from the start
    • no y: to the end
    • x and y can be negative
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 set

  • add

  • remove

  • len

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
    3
    np.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

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import numpy as np

# Create the following rank 2 array with shape (3, 4)
# [[ 1 2 3 4]
# [ 5 6 7 8]
# [ 9 10 11 12]]
a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])

# Two ways of accessing the data in the middle row of the array.
# Mixing integer indexing with slices yields an array of lower rank,
# while using only slices yields an array of the same rank as the
# original array:
row_r1 = a[1, :] # Rank 1 view of the second row of a
row_r2 = a[1:2, :] # Rank 2 view of the second row of a
print(row_r1, row_r1.shape) # Prints "[5 6 7 8] (4,)"
print(row_r2, row_r2.shape) # Prints "[[5 6 7 8]] (1, 4)"

# We can make the same distinction when accessing columns of an array:
col_r1 = a[:, 1]
col_r2 = a[:, 1:2]
print(col_r1, col_r1.shape) # Prints "[ 2 6 10] (3,)"
print(col_r2, col_r2.shape) # Prints "[[ 2]
# [ 6]
# [10]] (3, 1)"
  • 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
2
3
4
5
a = np.array([[1,2], [3, 4], [5, 6]])
bool_idx = (a > 2)
# [[False False]
# [ True True]
# [ True True]]

Datatypes

1
np.array(ARRAYDATA, dtype=ARRAYTYPE) 
  • * and / is elementwise

  • matrix multiplication or vector multiplication - dot

  • As 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, subplot and imshow