笔者使用python为3.4
1.字典
字典中取不存在的值的时候,会抛出keyerror错误,那么怎么实现返回默认值呢?
import collections
def inidefalut():
return "d"
index=collections.defaultdict(inidefalut)
print(index["a"])
这种写法会返回默认值“d”
有些字典是配置项参数需要避免使用者修改,又要允许管理员动态修改,那么怎么做呢
#encoding=utf-8
from types import MappingProxyType
data_origin={"adminpwd":123}
data_show=MappingProxyType(data_origin)
print(data_show["adminpwd"])
data_origin["adminpwd"]=456
print(data_show["adminpwd"])
# MappingProxyType 直接赋值报错
data_show["adminpwd"]=789
2.集合
python在集合里面的操作
# 集合的交并差对称差
a=set({1,2,3,5})
b=set({3,5,7})
# 交集
print(a&b)
# 并集
print(a|b)
# 差集
print(a-b)
# 异或 即只在a出现或只在b出现
print(a^b)
3.字符串
eval()函数可以将字符串形式的代码执行
cmd="1+3"
print(eval(cmd))
不是很精确但是大体能用的名字按拼音排序的方案
#encoding=utf-8
def chinese_sort(x):
x_sortcode=x.encode("GB18030")
return x_sortcode
a=["赵","钱","孙","李四","李大","晨晨"]
print(sorted(a,key=chinese_sort))
4.函数
函数是一等对象
class Person(object):
def __init__(self,name,trafficway):
self.name=name
self.traffic=trafficway
def __repr__(self):
return self.name+" : "+self.traffic(self)
def walk(p):
return p.name+" likes walk "
def bike(p):
return p.name +" bike a lot"
print(Person("tom",walk))
print(Person("Jerry",bike))
简单的装饰器的使用
def check_user(func):
def do_check(**kwargs):
if "user" in kwargs.keys():
if kwargs["user"] =="admin":
print("checksuccess")
return func(**kwargs)
print("user 验证失败")
return do_check
@check_user
def printhello(**kwargs):
print("hello")
return len(kwargs)
print(printhello(user="admin",age=1))
print("~~~~~~~~~~~~~~~")
print(printhello(user="admins",age=1))
5.变量
== 判断的是值相等 is 判断的是否为同一个变量
6.格式化
如 format(1.23456,'0.4f')
这里的 0.4f 称为格式规范微语言(format specification mini-language)
7.类
抽象类的实现
import abc
class Animal(abc.ABC):
@abc.abstractmethod
def hole(self):
'''animal voice'''
class Dog(Animal):
def hole(self):
print("wang")
class Cat(Animal):
def hole(self):
print("miao")
@Animal.register
class Duke(object):
def hole(self):
print("gaga")
Dog().hole()
Cat().hole()
Duke().hole()
print(issubclass(Duke,Animal))
8.正则表达式的基本使用
import re
pattent=re.compile(r"\w+")
testtext="what is your name sir"
print(any( pattent.finditer(testtext)))
for match in pattent.finditer(testtext):
print(match.group())
print(pattent.findall(testtext))
9.多线程及等待
import time
from concurrent import futures
def printandwait(x):
print(x)
time.sleep(0.2*x)
return str(x)+"ok"
with futures.ThreadPoolExecutor(max_workers=3) as exector:
todo=[]
for i in range(7):
f=exector.submit(printandwait,i)
todo.append(f)
for fok in futures.as_completed(todo):
print(fok.result())
print("success1")
with futures.ThreadPoolExecutor(max_workers=3) as exector:
todo=[]
for i in range(7):
f=exector.submit(printandwait,i)
todo.append(f)
futures.wait(todo)
print("success2")
10.json
推荐 jsonpickle 作为json类转换工具
网友评论