Sys & os
sys.argv[] 以list形式存储所有的命令参数,py test.py -c -m
打印所有会从文件名开始打印。”test.py -c -m”。
文件IO操作
程序不能直接对磁盘进行读写操作,使用系统调用接口。每次需要open,read,close,read()可以指定读取数据量大小,否则会一次读取全部可能爆内存。
常用语句:with open(program,’rw’) as: filehandle filehadnle.read/write()
for l in filehandle. x = input(“”).
b’’
Bytes literals are always prefixed with ‘b’ or ‘B’; they produce an instance of the bytes type instead of the str type. They may only contain ASCII characters; bytes with a numeric value of 128 or greater must be expressed with escapes.
str = ‘…’ literals = a sequence of Unicode characters (UTF-16 or UTF-32, depending on how Python was compiled)
bytes = b’…’ literals = a sequence of octets (integers between 0 and 255)
in
if x in next:depends on what’s next,
if next is a string, it checks for substring.
If it’s a different kind of iterable (list, tuple, dictionary…), then in checks for membership. eg:[1,2,3] in 2,true
in a dictionary be seen as be one of the keys.
sys.path
sys.path returns a list which contains all modules, including 3rd party module and current path. .append add wanted module path into the path, only take effets when running time.
sys.path.append(base):base is the address of referenced module.
lambda
defines a function with hidden name.lambda will return a function object. is a expression not a function,lambda x:x*x.
lambda x:load(x);
Complement a Linux command
find -name:find file in this folder
grep -rHn:parse file contents
ls -al:show up hidden folder which you may can’t access initially.
Change to Python3.x
print(x) is not required to have parenthsis.
Input in python 3.x:always treat as string, x = input(“please input”);x=’10’.
With Linux shell,should have #!/usr/bin/python3
or #!/usr/bin/env python3
to indicate file type and can be executed directly.
Standard type
multiple assignment:a=b=1////a,b=1,”whw”, use del a to free a variable reference.
standard type:number,string,list,tuple,dictionary.
String supports + as concatenation, [2:5] as substring and 2 as repetition.
all the items belonging to a list can be of different data type.
a[:],a[1:3].
The main difference between lists and tuples are − Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists.eg:tinytuple = (123, ‘john’)
dictionary:keys can be different type. dict[‘one’] = 1;dict.keys();dict.values();str(),int(),float(),set()(which has unique element and ca use add/remove) used for conversion.
boolean operator:and or not. power. is* indentifies whether 2 objects are the same. True,False.
iterator:use iter to get an iterator of list,a = iter(list),print(next(a)) can get you next value.
Number function:pow(x,y),fabs(x),max(),min(),sqrt(),exp(),log(),log10().
String methods
lstrip,rstrip:remove white space of given string. isdigit(),len(),find(str,begin,(end)) find substring.
List methods
list.append(obj),list.count(obj) count how many times obj occur.list.reverse().list.sort(function)
dict.clear(),dict.get(key,default=none),
Function
Params passed by referenced type, ie:they are reflected outside once changed.变量具有作用域限制。
Module
from x import temp, only introduce the temp function and ignore others.
Within a module, the module’s name (as a string) is available as the value of the global variable name. The code in the module will be executed, just as if you imported it, but only with the name set to “main“. Like below, the module can be called directly.
if name == “main“:
f = fib(100)
print(f)
Class && Object
class Employee:
current; #defined in class equivlant to a class variable, shared #by all instances
def init(self,name,age):
other methods all includes a argument called self.
setattr(obj,name,value);hasattr(obj,name);
getattr(obj,name);
build in attributes which can be used . to access anywhere:
name,dict:namespace of class,就是整个类的声明。
引用计数法清楚变量,索引。
An object’s reference count increases when it is assigned a new name or placed in a container (list, tuple, or dictionary). The object’s reference count decreases when it is deleted with del, its reference is reassigned, or its reference goes out of scope. When an object’s reference count reaches zero, Python collects it automatically.
Inheritence:class child(parent1,parent2):
xxx
Overriding methods:直接命名同名函数。
CGI
Commmon gateway interface:whenever a file is requested, it’s not returned directly but executed on server side and returns the result back to the browser.
Database API
import pymysql;
connect = pymysql.connect(“localhost”,”root”,”password”,”dbname”);
cursor = connect.cursor();
cursor.execute(sql);
connect.commit();
/#results = cursor.fetchall();
for row in results:
fname = row[0];
age = row[1];
parent = row[2];
try:
except:
connect.rollback();
Multithreading programming
Threading module
import threading;
For loop & if else
for cur in paragraph:xxx
for index in range(len(nums))
if nums[0] == 1://using column to indicate a coding block
Pandas
2 important data structures:
Series:1D array, using index to access value,
se.index():默认是0:len-1,se.values()
numpy数组操作:bool数组过滤,数乘将保持元素之间的索引
使用dict创建Series,键成为index
索引index可以就地更改,se.index = [dsad,dsad]
Dataframes:行的索引和列的索引;列索引column是dict的键,row索引是数字
直接df[‘state’]索引到的是整个列.
可以直接给某一列赋值为Series:df[‘state’] = se;
data[[‘one’,’two’]]提取两列出来
data.ix[2]:索引其中单独的一行
data[data>2]选择列过滤行
number of rows:len(df.index);number of cols:len(df.columns)
.loc()label based selection:
.loc[index,column]得到具体数值..loc[[‘a’,’b’,’c’],’A’:’C’]选取几个row和column
.iloc[[1,3,4],[2]]通过index进行选取,选取个别几列
series.size()直接获取大小,没有len()方法,df[‘’].str.len()返回选取长度
Python class call recursive functions inside the class
self.calculate(name,value);//with no self params already