创建set a = {1, 2, 3, 4, 5} a = set(obj) a = set() 空集合,{}只能用来创建空字典
方法
说明
替代语法
a.add(value)
将value添加到a
a.remove(value)
寻找第一个值并除去,不存在会报错
a.discard(value)
删除集合中指定的元素,不会报错
d.copy()
浅复制
a.pop(index)
删除并返回指定位置元素
a.clear()
清空a
a.update(b)
将b中元素融入a
a\=b
a.union(b)
a和b的不重复元素
a\b
a.intersection(b
交集
a&b
a.difference(b)
差集(存在于a,不存在于b)
a-b
a.issubset(b)
if a∈b return True
a.issuperset(b)
if b∈a return True
a.isdisjoint(b)
if
a
∩
b
=
∅
a∩b=\emptyset
a∩b=∅(交集) return True
列表、集合和字典推导式
list_comp=[expr for val in collection if condition]
set_comp ={expr for value in collection if condition}
dict_comp ={key-expr :value-expr for value in collection if condition}# list推导式等价for循环
list_comp =[]for val in collection:if condition:
list_comp.append(expr)
# 排列,组合,笛卡儿积:from itertools import combinations,permutations,product,combinations_with_replacement
# 自建迭代器defsquares(n=10):print('Generating squares from1 to {0}'.format(n **2))for i inrange(1, n +1):yield i **2#将return替换为yield即可返回迭代器
gen = squares()for x in gen:print(x, end=' ')
if 语句
if expression:
statements
elif expression:
statements
else:
statements
if 语句变体:value=[false-expr,true-expr][condition](利用list索引判断) 三元表达式:value=true-expr if condition else false-expr
>>>deftest(a,*args,**kwargs):print(a)print(args)print(kwargs)>>> test('a',1,'b',key1=2,key2='c')'a'(1,'b'){'key1':2,'key2':'c'}>>>deffib(n):# write Fibonacci series up to n..."""Print a Fibonacci series up to n."""... a, b =0,1...while a < n:...print(a, end=' ')... a, b = b, a+b
...print()...>>># Now call the function we just defined:... fib(2000)011235813213455891442333776109871597
所以Python3里有了这个新特性,可以给参数、函数返回值和变量的类型加上注解,不过这个仅仅是注释而已,对代码的运行来说没有任何影响,变量的真正类型还是会有Python解释器来确定,你所做的只是在提高代码的可读性,让 IDE 了解类型,从而提供更准确的代码提示、补全和语法检查,仅此而已。
注解是以字典形式存储在函数的 __annotations__属性中,对函数的其它部分没有任何影响。
>>>defadd(x:int, y:int)->int:...return x+y
>>>deff(ham:42, eggs:int='spam')->"Nothing to see here":...print("Annotations:", f.__annotations__)...print("Arguments:", ham, eggs)...>>> f('wonderful')
Annotations:{'eggs':<class'int'>,'return':'Nothing to see here','ham':42}
Arguments: wonderful spam
In [89]: seq1 =['foo','bar','baz']
In [90]: seq2 =['one','two','three']
In [92]:list(zip(seq1, seq2))
Out[92]:[('foo','one'),('bar','two'),('baz','three')]
In [95]:for i,(a, b)inenumerate(zip(seq1, seq2)):....:print('{0}: {1}, {2}'.format(i, a, b))....:0: foo, one
1: bar, two
2: baz, three
排列组合
from itertools import product,permutations,combinations
这里的 another 就是一个闭包,闭包本质上是一个函数,它由两部分组成,printer 函数和变量 msg。闭包使得这些变量的值始终保存在内存中。
示例: 闭包常用于解偏微分方程,如下例:求解陨石运动轨迹
运动半径:
r
=
x
2
+
y
2
+
z
2
r=\sqrt{x^2+y^2+z^2}
r=x2+y2+z2 单位向量:
r
^
=
r
⃗
r
\hat{r}=\cfrac{\vec{r}}{r}
r^=rr 加速度:
d
v
⃗
d
t
=
−
G
M
r
2
⋅
r
^
\cfrac{d\vec{v}}{dt}=-\cfrac{GM}{r^2}\cdot\hat{r}
dtdv=−r2GM⋅r^ 速度:
v
⃗
=
d
r
⃗
d
t
\vec{v}=\cfrac{d\vec{r}}{dt}
v=dtdr 使用 scipy 包求解坐标 (x,y,z)
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import solve_ivp
defgravity(GM=1):'''
dr/dt=v
r_norm=sqrt(x^2+y^2+z^2)
dv/dt=-GM/dot(r,r)*r/r_norm
'''defforce(t,X_and_V):'GM loading...'
x,y,z,vx,vy,vz=X_and_V
r=np.array([x,y,z])
v=np.array([vx,vy,vz])
dr=v
r_norm=np.linalg.norm(r)
dv=-GM/np.dot(r,r)*r/r_norm
return np.concatenate([dr,dv])return force
r0=(20,30,0)
v0=(0.8,0.5,0)
t0,t1=0,100
F=gravity(GM=1000)
motion=solve_ivp(fun=F,t_span=(t0,t1),y0=r0+v0, t_eval=np.linspace(t0,t1,1001))
plt.plot(motion.y[0,:],motion.y[1,:])
plt.show()
from functools import wraps
defdecorator_name(f):@wraps(f)#加载wraps是为了原函数的名字和注释文档不被重写(docstring)defdecorated(*args,**kwargs):print('I am do something')ifnotTrue:return"Function will not run"return f(*args,**kwargs)return decorated
@decorator_namedeffunc():return("Function is running")