1 python代码执行跟踪
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)
3. python 判断是文件或者目录
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
5. 字典中加入其它字典元素
现在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。
阅读(2525) | 评论(0) | 转发(0) |