美文网首页
Python学习-应用技巧

Python学习-应用技巧

作者: huozhihui | 来源:发表于2017-09-14 11:02 被阅读0次
  1. 获取所有大写、小写字母和数字的方法
>>> import string
>>> string.ascii_uppercase        # ABCDEFGHIJKLMNOPQRSTUVWXYZ
>>> string.ascii_lowercase        # abcdefghijklmnopqrstuvwxyz
>>> string.digits                 # 0123456789
>>> string.ascii_letters          # 所有大小写
  1. 生成随机码
>>> import string
>>> import random
>>> def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
...    return ''.join(random.choice(chars) for _ in range(size))
...
>>> id_generator()
'G5G74W'
>>> id_generator(3, "6793YUIO")
'Y3U'
  1. 测量脚本或方法运行时间
>>> import cProfile
>>> cProfile.run('foo()')

# 测量脚本
python -m cProfile myscript.py
  1. 通过方法名的字符串来调用该方法
>>> class Foo():
...     def run(self):
...             print 'run method'
...

# 方法一:使用eval
>>> foo = Foo()
>>> method = eval('foo.run')
>>> method()
run method

#方法二:使用getattr(推荐)
>>> foo = Foo()
>>> method = getattr(foo, 'run')
>>> method()
run method
  1. 字符串翻转
>>> 'hello'[::-1]
  1. yield的用法
def fab(max): 
    n, a, b = 0, 0, 1 
    while n < max: 
        yield b 
        # print b 
        a, b = b, a + b 
        n = n + 1 

结论:一个带有 yield 的函数就是一个 generator,它和普通函数不同,生成一个 generator 看起来像函数调用,但不会执行任何函数代码,直到对其调用 next()(在 for 循环中会自动调用 next())才开始执行。虽然执行流程仍按函数的流程执行,但每执行到一个 yield 语句就会中断,并返回一个迭代值,下次执行时从 yield 的下一个语句继续执行。看起来就好像一个函数在正常执行的过程中被 yield 中断了数次,每次中断都会通过 yield 返回当前的迭代值。

  1. range和xrange区别
for i in range(1000): pass

for i in xrange(1000): pass
  • range: 生成一个 1000 个元素的 List。
  • xrange: 不会生成一个 1000 个元素的 List,而是在每次迭代中返回下一个数值,内存空间占用很小。因为 xrange 不返回 List,而是返回一个 iterable 对象。
  1. 检查一个字符串是否是一个数字
>>> "123".isdigit()
  1. 将列表等分成同样大小的块
>>> L = range(1, 100) 
>>> n = 10
>>> tuple(L[i:i+n] for i in xrange(0, len(L), n))
  1. 判断文件是否存在
>>> import os
>>> os.path.isfile(fname)
  1. 对字典排序
>>> import operator
>>> x = {1: 2, 3: 4, 4:3, 2:1, 0:0}
# 通过字典键排序
>>> sorted_x = sorted(x.items(), key=operator.itemgetter(0))

#通过字典值排序
>>> sorted_x = sorted(x.items(), key=operator.itemgetter(1))

或者

sorted(d.items(), key=lambda x: x[1])
  1. 在终端里显示颜色
>>> from termcolor import colored
>>> print colored('hello', 'red'), colored('world', 'green')
  1. 在循环中获取列表索引(数组下标)
>>> L = [8, 23, 45, 12, 78]
>>> for idx, val in enumerate(L):
        print ids, val

相关文章

网友评论

      本文标题:Python学习-应用技巧

      本文链接:https://www.haomeiwen.com/subject/bonksxtx.html