python小型函數技巧積累,python函數技巧
preface:在前進的路上遇到的python各種小函數技巧積累。
enumerate:枚舉
format:格式化輸出。
對字串進行輸出時,print加逗號可破,但當字串變數多了起來的時候,同字串常量放在一起,逗號就變多了。不太方便。通過format類進行格式化,將變數都放在一起,能夠更加方便地控制輸出格式。具體的fomat文法說明網上部落格也是一大堆,如http://www.2cto.com/kf/201312/262068.html,稍微提到的一些。當然,還有最重要的官網的資料的了:https://docs.python.org/2/library/string.html。都可以參考參考。
age = 25name = 'Caroline'print('{0} is {1} years old. '.format(name, age)) #輸出參數print('{0} is a girl. '.format(name))print('{0:.3} is a decimal. '.format(1.0/3)) #小數點後三位print('{0:_^11} is a 11 length. '.format(name)) #使用_補齊空位print('{first} is as {second}. '.format(first=name, second='Wendy')) #別名替換print('My name is {0.name}'.format(open('out.txt', 'w'))) #調用方法print('My name is {0:8}.'.format('Fred')) #指定寬度drinks={"coffee","tea","milk","water"}for index,drink in enumerate(drinks):s="item: "+str(index)+" is "+drinkprint sprint "item:",index,"is",drinkprint "item: {} is {} ".format(index,drink)
yield:產生器
def fib_generator():a=0b=1while True:yield aa,b=b,a+bmin_number=100print fib_generator()for number in fib_generator():print numberif number > min_number:print number,min_numberbreak<generator object fib_generator at 0x0000000002173090>01123581321345589144144 100
可以看出,帶有yield的函數,具有迭代能力,是一個迭代器。以前遇到過,當資料量大了起來的時候,就變得很有用了。具體參考:http://www.ibm.com/developerworks/cn/opensource/os-cn-python-yield/,沒仔細找到官網的介紹。
還有一些小技巧參考:https://www.airpair.com/python/posts/python-tips-and-traps.