Introduction to Python

Reference:
CS224N
Numpy Reference
Python Documentation
CS231N Python Tutorial
Python and Function Programming
Best Practice for Using Fuction Programming in Ptyon

1、Basic

list、sets、dict、tuple

1
2
3
4
5
6
7
8
9
10
11
12
13
14
lis = [1,2,3,"a","b",1,2]
print("list: type=",type(lis),"value=",lis)

sets = {1,2,3,"a","b",1,2}
print("set: type=",type(sets), "value=",sets)

dicts = {"a":1,"b":2,"a":3,"d":4,1:"f"}
print("dicts: type=",type(dicts), "value=",dicts)

tu = (1,2,2,4)
print("tuple: type=", type(tu), "value= ", tu)

# *表达式 : 将一个含有N个元素的数据结构类型分解成所需的几部分
first,second, *mid, last = range(10)


2、Comprehensions

Comprehensions
flat list in one line

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
list_of_lists = [[1,2,3],[4,5,6]]
print("list_of_lists[1][1] =",list_of_lists[1][1])

mlist = [e**2 for e in [1,2,3,4,5] if e % 2 ==0 ]
print(mlist)

# filter()和map(): python2返回列表, python3返回迭代器
iterator1 = filter(lambda e : e %2 == 0, [1,2,3,4,5])
iterator2 = map(lambda e : e**2, [1,2,3,4,5])
iterator3 = map(lambda x, y : x+y, [1,2,3],[4,5,6])
s = sum(x*y for (x,y) in zip([1,2,3,4], [5,6,7,8]))
print("sum: ", s)

for i in iterator1:
print("filter: ", i)

for i in iterator2:
print("map(x): ", i)

for i in iterator3:
print("map(x,y): ", i)

a_2d_list = [[i+j for i in range(3)] for j in range(4)]
print("",a_2d_list)

a = { e for lis in a_2d_list for e in lis }
print("flat 2d list: ", a)

import itertools
for i in itertools.chain(a_2d_list):
print("itertools chain: ", i)

for i in itertools.chain(*a_2d_list):
print("itertools chain *: ", i)



####
def fun1():
print(1)

def fun2():
print(2)

def fun3():
print(3)
executions = lambda f: f()
for i in map(executions, [fun1, fun2, fun3]):
i

###
cube = lambda x : x**3
square = lambda x : x**2
increment = lambda x : x + 1
decrement = lambda x : x - 1

def call(x, f):
return f(x)

from functools import reduce
print(reduce(call, [square, increment,cube, decrement]))
print(call(3,cube))


3、sorting list

1
2
3
4
5
sortList = sorted([4,2,1,7,3,2])
print(sortList)

sortList2 = sorted([(5,"c"),(3,"b"),(7,"a"),(1,"b")])
print(sortList2)

4、numpy and scipy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import numpy as np
#ndarray
ones = np.ones(3)
print("type:",type(ones),"shape:", ones.shape, ", value:", ones)

ones = np.ones([3,4])
print("type:",type(ones),"shape:", ones.shape, ", value:", ones)


ones = np.random.rand(3,3)
print("type:",type(ones),"shape:", ones.shape, ", value:", ones)

ones = np.zeros([2,2])
print("type:",type(ones),"shape:", ones.shape, ", value:", ones)

ones = np.array([[0,1,2],[3,4,5],[6,7,8]])

two = np.asarray([[1,1,2],[3,4,5],[6,7,8]])
print("add:", ones+two)
print("multiple: ", ones*two)
print("divide: ", ones/two)
print("dot: ", np.dot(ones, two))
print("dot: ", np.dot([1,2,3],[1,2,3]))

5、Broadcasting

1
2
3
4
5
6
7
8
9
10
11
x = np.array([[1,10,20,30],[1,2,3,4]])
print(x+100)
print(x*100)
print(np.sin(x))

xx = np.array([[[1,5,6],[2,3,4]],[[1,5,6],[2,3,4]]]) #shape(2,2,3)
yy = np.array([[2,3,4,5],[1,1,1,1],[0,0,0,0]]) #(3,4)
print("hardest broadcast: shape(2,2,3)*shape(3,4)=shape(2,2,4)",", value=", np.matmul(xx,yy))

print("axis 0: sum=",np.sum(x,axis=0), ", max=", np.max(x, axis=0))
print("axis 1: sum=",np.sum(x,axis=1), ", min=", np.min(x, axis=1))

6、plot

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0, 3*np.pi, 0.1)
y_sin = np.sin(x)
y_cos = np.cos(x)

plt.plot(x, y_sin)
plt.text(5,0, "write your text anywhere")
plt.scatter(point_x, point_y)
plt.plot(x, y_cos)
plt.xlabel("x axis label")
plt.ylabel("y axis label")
plt.title("Sin Cos Log")

point_x = np.arange(0.1, 3*np.pi, 0.3)
point_y = [np.log2(e) for e in point_x]

plt.legend(["sin", "cos", "log"])
plt.show()

7、iterators、generators、for loop

iterators and generators
To create a Python iterator object, you will need implement two methods in your iterator class:

  • iter
  • next
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    import random

    class MyIter(object):
    li = [1,2,3,4,5,6,7,8,9]

    def __iter__(self):
    return self
    def __next__(self):
    return random.choice(self.li)

    c = MyIter()
    lis = [next(c) for i in range(7)]
    print(lis)

    for i in c:
    print(i)

Python generator is implemented by defining a function using keyword “yield”:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class MyGenerator(object):
def ch(self):
yield "a"
yield "b"
yield "c"
yield "d"

g = MyGenerator()
gg = g.ch()
l = [next(gg) for _ in range(3)]
print(l)


def generateInt():
yield 10
yield 9
yield 8
yield 7
yield 6
yield 5
ggg = generateInt()
s = [next(ggg) for i in range(6)]
print(s)

8. argparse

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import argparse


parser = argparse.ArgumentParser(description="This line will print by -h")

#1. 位置参数
parser.add_argument("e")

#2. 可选参数(必须指定)
parser.add_argument("-v", "--verbosityyyyy", help="add output verbosity")


#3. 可选参数(默认)
parser.add_argument("-a", "--act", default="a_default_value", help="add output verbosity")

#4. 参数类型
parser.add_argument("-n", type=int, help="input number")


#5. 限定取值范围
parser.add_argument("--number", type=int, choices=[1,2,3])

#6. 互斥参数(如下p、q只能存一个)
group = parser.add_mutually_exclusive_group()
group.add_argument("-q")
group.add_argument("-p")


args = parser.parse_args()
flags, _ = parser.parse_known_args()

print("args.verbosityyyyy =", args.verbosityyyyy)
print("args.e =", args.e)
print("args.act =", args.act)
print("args.n =", args.n)
print("args.number =", args.number)
print("args.q =", args.q)

print(flags)

$ python test_argparse.py hi -v eee -n 12 –number 1 -p 0
args.verbosityyyyy = eee
args.e = hi
args.act = a_default_value
args.n = 12
args.number = 1
args.q = None
Namespace(act=’a_default_value’, e=’hi’, n=12, number=1, p=’0’, q=None, verbosityyyyy=’eee’)