python -m trace --trace CheckDigit.py
2 python判断是否为数字
点击(此处)折叠或打开
- def CheckDigit(Num):
- try:
- Num = int(Num)
- except:
- print "%s is not a digit"%str(Num)
- if isinstance(Num, int):
- print "%s is a digit"%str(Num)
- else:
- print "%s is not a digit"%str(Num)
os.path.isfile(file_name)
os.path.isdir(dir_name)
4. python中的*args和**kwargs
首先这两个是传给python函数的参数,其中*args在前,**kwargs在后,其中args是无名参数,**kwargs是有名参数,比如foo(1,2,3,4,a=1,b=2,c=3,d=4),其中args是(1,2,3,4)的一个元组,而kwargs是{‘a’=1,‘b’=2,‘c’=3,‘d’=4}的一个字典。**kwargs的一个应用是创建一个字典。
点击(此处)折叠或打开
- def mkdict(**kwargs):
- return kwargs
a是个字典,b是个字典
a.update(b)
现在a是a和b的并集。
6. 判断一个字典中是否有某个值
a.has_key(key)返回True或者False
7. 判断一个字典是否有某个值,有就返回某个值,否则抛出异常
a.get(key,Error_message)
有的话返回value,否则返回Error_message
8. 两个字典求并集
点击(此处)折叠或打开
- def timeo(func, n=1000):
- def void():
- pass
- start = time.clock()
- for i in range(n):
- void()
- stend = time.clock()
- overhead = stend - start
- start = time.clock()
- for i in range(n):
- func()
- stend = time.clock()
- thetime = stend - start
- return func.__name__, thetime - overhead
- to500 = {}
- for i in range(500):
- to500[i] = 1
- evens = {}
- for i in range(0,1000,2):
- evens[i] = 1
- def badslowlyway():
- insection = []
- for item in to500.keys():
- if item in evens.keys():
- insection.append(item)
- return insection
- def simplyway():
- insection = []
- for item in to500.keys():
- if evens.has_key(item):
- insection.append(item)
- return insection
- def pyth22way():
- return [ x for x in to500 if x in evens]
- def filterway():
- return filter(to500.has_key, evens.keys())
点击(此处)折叠或打开
- [root@node5 python_scripts]# python insection.py
- badslowlyway:7.62
- simplyway:0.17
- pyth22way:0.08
- filterway:0.03
其中后面的效率更快,代码更pythonic。