generator & list on python

generator不同於list,沒有list,且只能遊走一次.
下面的code可以發現generator的元素是在被用的時候才產生.

import time

b=[time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) for i in range(3)]

time.sleep(1)
print("A:",time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
time.sleep(1)

for ii in b:
  print("B:",ii)
  time.sleep(1)

###########################################################################

b=(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) for i in range(3))

time.sleep(1)
print("C:",time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
time.sleep(1)

for ii in b:
  print("D:",ii)
  time.sleep(1)

[python練習] numpy

引用

import numpy as np;

1維陣列

a = np.array([1, 2, 3]);

2維陣列

a = np.array([ [1, 2, 3], [4, 5, 6] ]);

3維陣列

a = np.array([ [ [1, 2, 3], [4, 5, 6] ], [ [7, 8, 9], [10, 11, 12] ] ]);

內積 (vector dot)

vector dot

v1 = np.array([1, 2, 3]);
v2 = np.array([4, 5, 6]);
v3 = np.dot(v1,v2); #v3 = 1*4 + 2*5 + 3*6 = 4 + 10 + 18 = 32
print(v3);

矩陣相乘 (matrix multiplication)

matrix_multiplication

m1 = np.array([ [1, 2, 3], [4, 5, 6] ]);      #size: 2*3
m2 = np.array([ [1, 2 ], [3, 4], [5, 6] ]);   #size: 3*2
m3 = np.matmul(m1,m2); # m3= [ [ 1*1+2*3+3*5 1*2+2*4+3*6] [ 4*1+5*3+6*5 4*2+5*4+6*6 ] ] = [ [ 22 28 ] [ 49 64 ] ]
print(m3);

元素相乘 (multiply)

  • 不常用
m1 = np.arange(1,5).reshape(2,2); # m1 = [ [ 1 2 ] [ 3 4 ] ]
m2 = np.arange(0,4).reshape(2,2); # m2 = [ [ 0 1 ] [ 2 3 ] ]
m3 = np.multiply(m1,m2);          # m3 = [ [ 1*0 2*1 ] [ 3*2 4*3 ] ] = [ [ 0 2 ] [ 6 12 ] ]
print(m3);

原始碼

[python練習] pyplot

import matplotlib.pyplot as plt
import numpy as np

#產生隨機資料
x_data = np.linspace(-100, 100, 300)[:, np.newaxis];
#加入雜訊
noise = np.random.normal(0, 300, x_data.shape);
y_data = np.square(x_data) - 0.5 + noise;

plt.plot(x_data, y_data, 'g.');

#動態繪製sin曲線
x = np.arange(-100,100) 
for i in range(1000):
  #嘗試移除畫過的sin曲線,第一次會發生錯誤,因此用try/except
  try:
    lines.pop(0).remove()
  except Exception:
    pass
  #重新計算y值
  y = 1000*np.sin((x+i) * np.pi/ 9.0)
  #繪製sin曲線
  lines=plt.plot(x,y,'r-')
  #延遲0.1秒
  plt.pause(0.1)

原始碼