"""
迭代器:
使用迭代方法的好处:
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)