- 獲取所有大寫穗慕、小寫字母和數(shù)字的方法
>>> import string
>>> string.ascii_uppercase # ABCDEFGHIJKLMNOPQRSTUVWXYZ
>>> string.ascii_lowercase # abcdefghijklmnopqrstuvwxyz
>>> string.digits # 0123456789
>>> string.ascii_letters # 所有大小寫
- 生成隨機(jī)碼
>>> 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'
- 測(cè)量腳本或方法運(yùn)行時(shí)間
>>> import cProfile
>>> cProfile.run('foo()')
# 測(cè)量腳本
python -m cProfile myscript.py
- 通過方法名的字符串來調(diào)用該方法
>>> 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
- 字符串翻轉(zhuǎn)
>>> 'hello'[::-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
結(jié)論:一個(gè)帶有 yield 的函數(shù)就是一個(gè) generator,它和普通函數(shù)不同妻导,生成一個(gè) generator 看起來像函數(shù)調(diào)用逛绵,但不會(huì)執(zhí)行任何函數(shù)代碼怀各,直到對(duì)其調(diào)用 next()(在 for 循環(huán)中會(huì)自動(dòng)調(diào)用 next())才開始執(zhí)行。雖然執(zhí)行流程仍按函數(shù)的流程執(zhí)行术浪,但每執(zhí)行到一個(gè) yield 語句就會(huì)中斷瓢对,并返回一個(gè)迭代值,下次執(zhí)行時(shí)從 yield 的下一個(gè)語句繼續(xù)執(zhí)行胰苏∷队迹看起來就好像一個(gè)函數(shù)在正常執(zhí)行的過程中被 yield 中斷了數(shù)次,每次中斷都會(huì)通過 yield 返回當(dāng)前的迭代值硕并。
- range和xrange區(qū)別
for i in range(1000): pass
for i in xrange(1000): pass
- range: 生成一個(gè) 1000 個(gè)元素的 List法焰。
- xrange: 不會(huì)生成一個(gè) 1000 個(gè)元素的 List,而是在每次迭代中返回下一個(gè)數(shù)值倔毙,內(nèi)存空間占用很小埃仪。因?yàn)?xrange 不返回 List,而是返回一個(gè) iterable 對(duì)象陕赃。
- 檢查一個(gè)字符串是否是一個(gè)數(shù)字
>>> "123".isdigit()
- 將列表等分成同樣大小的塊
>>> L = range(1, 100)
>>> n = 10
>>> tuple(L[i:i+n] for i in xrange(0, len(L), n))
- 判斷文件是否存在
>>> import os
>>> os.path.isfile(fname)
- 對(duì)字典排序
>>> 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])
- 在終端里顯示顏色
>>> from termcolor import colored
>>> print colored('hello', 'red'), colored('world', 'green')
- 在循環(huán)中獲取列表索引(數(shù)組下標(biāo))
>>> L = [8, 23, 45, 12, 78]
>>> for idx, val in enumerate(L):
print ids, val