Python:Quick Reference

Quick Reference


String

s="foo bar"
s='foo bar'
s=r"c:\dir\new"   #raw string 

s='''Hello
world
'''

s.join(" baz")
len(s)

"{}+{}={}".format(3,2,5)


List

L=[1,2,3,4,5]
L[0]
L[-1]
L[0:3]
L[-2:]
L[1:4]=[7,8]  #substitute
del L[2]      # remove elements
L.append(x)   # x is a value 
L.remove(x)
L.extend(L2)  # or: L3=L+L2 
L.pop()
L.sort()
x in L 
L.index(x)
[x*2 for x in L if x>2]

Tuple

x=1,2,3
x=(1,2,3)
x[1]
a,b,c=x 

Dictionary

D={'f1':10,'f2'L20}
D=dict(f1=10,f2=20)

keys=('a','b','c')
D=dict.fromkeys(keys)

for k in D: print(k)
for v in D.values():print(v)
for k,v in D.items():
list(D.keys())
sorted(D.keys())

D={}


Set

S={1,3,5}
L=[1,3,1,5,3]
S=set(L)
if (3 in S):
S1+S2,S1-S2,S1^S2,S1|S2 


Loop

for x in range(6):
for x in range(1,6):
for x in range(1,6,2):

for k,v in D.iterms():
	print(k,v)

L=[1,3,5]
for i,v in enumerate(L):
for x,y in zip(L1,L2):
for i in sorted(set(L)): print(i)
for x in reversed(L1):


Function

def foo(arg1,*args,**dic):
	"""Example documentation string.
	   This function dose not do anything special
	"""
def foo(a,b,c=0):

L=[1,2,3]
foo(*L)
D={'a':10,'b':20}
foo(**D)

foo.__doc__


IO/File

f=open('test.txt','w')
f.write('bla ....')
f.close()

for line in open('test.txt'): print(line,end="")

L=open('test.txt').readlines()

f=os.fdopen(os.open('test.txt',os.O_WRONLY|os.O_EXCL),'w')

print('Error!',file=sys.stderr,flush=True)

os.rename(from,to)
os.chmod(file,0700)


Exception

try:
	raise TypeError("arg")
except (RuntimeError,NameError):
	pass 
except:
	info=sys.exc_info()
	print(info[0])
	print(info[1])
	traceback.print_tb(info[2])
	raise 
else:
	...
finally:
	...

OOP

class Person:
	ID=0         #static variable
	def __init__(self,name,age=0):
		self.name=name
		self.age=age
		Person.ID+=1
		self.ID=Person.ID
	def lastName(self):
		return self.name.split()[-1]
	def __str__(self):
		return "{}({},{})'.format(self.__class__.__name__,self.name,self.age)

class Worker(Person):
	def __init__(self,name,position,age=0):
		super().__init__(name,age)
		self.position=position 
	def __str__(self):
		return "{}({},{},{})".format(self.__class__.__name__,self.name,self.position,self.age)

bob=Worker("Bob Smith","developer",25)
print(bob)

Useful API



Q=collections.deque([10,20,30])
Q.append(40)
Q.popleft()


f=open('myobj.dat','w')
pickle.dump(x,f)
f=open('myobj.dat','r')
x=pickle.load(f)



conn=sqlite3.connect('data.db')
c=conn.cursoe()
c.execute('SELECT * FROM employees')
for row in c:
	print(row[0])
conn.commit()
conn.close()

db=shelve.open('file')
db['x']=y
db.close()

Python库collections
pickle模块
Python 数据库操作- sqlite3 模块
快速入门Shelve:Python数据存储利器


Module sys

sys.argv sys.stdin sys.stdout sys.stderr sys.path sys.platform sys.version 

Module os


os.pathsep os.sep os.pardir os.curdir os.linsep
os.startfile('index.html')
os.popen('ps ax').readlines()
os.listdir('/usr/local')
os.glob('*.txt')

os.path.split('/usr/bin/go.sh')
os.path.joint('/usr/local','go.sh')
os.path.splitext('/usr/local/go.sh')
os.path.abspath('../bin/go.sh')
os.path.isfile('go.sh')

os.environ.get('PYTHONSTARTUP')

for (dir,subdirs,files) in os.walk('/tmp'):
	for f in files: print(f)

python中的os模块


Functional programming

f=lambda x: x+10
f(5)
L=[1,4,7]
for x in filter(lambda i: i<5,L):
for x in map(lambda: x:x*2,L):

Module subprocess


res=subprocess.run(['hostname','-f'],stderr=subprocess.DEVNULL)
res=subprocess.run('ps aux | grep ^root',shell=True)
output=subprocess.check_output(['mycmd','myarg'],universal_newlines=True)

subprocess文档
The subprocess Module: Wrapping Programs With Python
Python Subprocess Interactive
python-execute-program-or-call-a-system-command
深入理解python中的subprocess模块
Python标准库 subprocess 模块多进程编程详解Subprocess Python Stdout


Python Concurrency

Multiprocessing For-Loop in Python
Concurrent For-Loop With a ThreadPool in Python
threading — Thread-based parallelism
用 OpenMP 并行多核加速 Python


mpi.py

from mpi4py import MPI

comm=MPI.COMM_WORLD
rank=comm.Get_rank()

print(rank)

if rank==0:
    data={'a':7,'b':3.14}
    comm.send(data,dest=1,tag=11)
elif rank==1:
    data=comm.recv(source=0,tag=11)
    print(data)

遍历python字典


for name in boundary:
    print(name)

for key in boundary.keys():
    print(key)

for value in boundary.values():
    print(value)

for name,value in boundary.items():
    print(name,value)

for index,(k,v) in enumerate(boundary.items()):
    print(index,k,v)

#挑选
wall={k:v for k,v in boundary.items() if v.id>=1 and v.id <4}
print(wall)

#迭代器
iterator=iter(boundary)
while True:
    try:
        k=next(iterator)
        v=boundary[k]
        print('iterator:',k,v)
    except StopIteration:
        break

用python调用三维向量和矩阵

import numpy as np

v1=np.array([1.0,2.0,3.0])
v2=np.array([4.0,5.0,6.0])

dot_product=np.dot(v1,v2)
cross_product=np.cross(v1,v2)


Python常用的几种画图工具: MatplotlibSeabornPlotlyBokehvtk


PyOpenGL
PyOpenGL进行OpenGL编程
Pyglet Python and OpenGL Tutorial
Pyglet


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值