python小型函數技巧積累,python函數技巧

來源:互聯網
上載者:User

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.



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.