"""
迭代器:
使用迭代方法的好處:
1.可節省內存空間
2.會從容器裏面挨個取值,直到取完爲止
"""
class YourRange():
def __init__ (self, start, end):
self.value = start
self.end = end
def __iter__(self):
return self
def __next__(self):
if self.value >= self.end:
raise StopIteration
cur = self.value
self.value +=1
return cur
# 實例化:
yr = YourRange(5, 12)
for e in yr:
print(e)
import matplotlib.pyplot as plt
plt.plot(list(range(10,20)), list(range(0,10)), c='r')
plt.show()
import seaborn as sns
sns.barplot(list(range(10,20)), list(range(0,10)))
plt.show()
import numpy as np
import matplotlib.pyplot as plt
nx , ny = (5,3)
x = np.linspace(0, 1, nx)
x
y = np.linspace(0, 1, ny)
y
# 使用meshgrid 生產網格點
xv , yv = np.meshgrid(x, y)
xv, yv
plt.scatter(xv.flatten(), yv.flatten(), c='red')
plt.xticks(ticks=x)
plt.yticks(ticks=y)
plt.show()
# 繪製曲面圖
from mpl_toolkits.mplot3d import Axes3D
x = np.arange(-5, 5, 0.25)
y = np.arange(-5, 5, 0.25)
X,Y = np.meshgrid(x, y) # x-y 平面的網格
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
fig = plt.figure()
ax = Axes3D(fig)
plt.xticks(ticks=np.arange(-5, 6))
plt.yticks(ticks=np.arange(-5, 6))
ax.plot_surface(X, Y, Z, cmap=plt.get_cmap('rainbow'))
plt.show()
# 等高線圖
fig = plt.figure()
ax = Axes3D(fig)
plt.xticks(ticks=np.arange(-5, 6))
plt.yticks(ticks=np.arange(-5, 6))
ax.contourf(X, Y, Z, zdir='z', offset=-1, cmap=plt.get_cmap('rainbow'))
plt.show()
"""
在交互模式下,上一次打印出來的表達式被賦值給變量 _
In [8]: 2*3.02+1
Out[8]: 7.04
In [9]: 1+_
Out[9]: 8.04
"""
"""
使用單引號和雙引號的微妙不同
使用一對雙引號時,打印下面串無需轉義字符:
print("That isn't a horse")
使用單引號時,需要添加轉義字符 \:
print('That isn\'t a horse')
"""
# 符串字面值可以跨行連續輸入;一種方式是用一對三重引號:""" 或 '''
print("""You're just pounding two
...: coconut halves together.""")
# 數字 * 字符串
3 * "py"
"""
直接使用 x 和 not x 判斷 x 是否爲 None 或空
"""
# 直接使用 enumerate 枚舉容器,第二個參數表示索引的起始值
x = [1,3,5]
for i,e in enumerate(x, 10): # 10爲索引的起始值
print(i, e)
# 判斷字符串是否包含 ***某個子串***,使用in明顯更加可讀:
x = 'zen_of_python'
if 'zen' in x:
print('zen is in')
# 使用 zip 打包後結合 for 使用輸出一對, 更加符合習慣
keys = ['a', 'b', 'c']
values = [1, 3, 5]
for k,v in zip(keys, values):
print(k, v)
# 串聯字符串,更習慣使用 join:
chars = ['P', 'y', 't', 'h', 'o', 'n']
name = ''.join(chars)
print(name)
### 列表生成式:(高效)
data = [1,2,3,5,8]
result = [i*2 for i in data if i&1] # 奇數乘以 2
print(result) # [2, 6, 10]
# 字典生成式
keys = ['a', 'b', 'c']
values = [1,3,5]
d = {k: v for k, v in zip(keys, values)}
print(d)
# lambda 函數使用方便,主要由入參和返回值組成,被廣泛
# 使用在 max, map, reduce, filter 等函數的 key 參數中
x = [1, 3, -5]
# 求 x 中絕對值最大的元素,key函數確定abs(x)作爲比較大小的方法:
y = max(x, key = lambda x: abs(x))
print(y)
# map 函數映射 fun 到容器中每個元素,並返回迭代器 x
x = map(str, [1,2,3])
for e in x:
print(e, type(e))
# reduce 是在 functools 中,
# 第一個參數是函數,其必須含有 2 個參數,最後歸約爲一個標量
from functools import reduce
x = list(range(1,6,2))
y = reduce(lambda p1, p2: p1*p2, x)
print(y)
# 使用 filter 找到滿足 key 函數指定條件的元素,並返回迭代器
x = list(range(1,6,1))
odd = filter(lambda e: e%2 ,x)
for i in odd:
print(i)
odd = [e for e in x if not e%2]
print(odd)