python counter、閉包、generator

來源:互聯網
上載者:User

標籤:簡單   class   generator   top   函數   變數   並且   port   解決   

 1、python庫——counter
from collections import Counterbreakfast=[‘spam‘,‘spam‘,‘eggs‘,‘spam‘]breakfast_counter=Counter(breakfast)breakfast_counter    #Counter({‘eggs‘: 1, ‘spam‘: 3})#函數 most_common() 以降序返回所有元素,或者如果給定一個數字,會返回該數字前的的元素breakfast_counter.most_common() #[(‘spam‘, 3), (‘eggs‘, 1)]breakfast_counter.most_common(1) #[(‘spam‘, 3)]#可以組合計數器lunch=[‘eggs‘,‘eggs‘,‘bacon‘]lunch_counter=Counter(lunch)lunch_counter     #Counter({‘bacon‘: 1, ‘eggs‘: 2})#第一種組合計數器的方式是使用 + 從一個計數器加上另一個breakfast_counter+lunch_counter    #Counter({‘bacon‘: 1, ‘eggs‘: 3, ‘spam‘: 3})#第二種組合計數器的方式是使用 -  從一個計數器去掉另一個breakfast_counter-lunch_counter   #Counter({‘spam‘: 3})lunch_counter-breakfast_counter   #Counter({‘bacon‘: 1, ‘eggs‘: 1})#第三種組合計數器的方式是使用 &  得到二者共有的項breakfast_counter&lunch_counter   #Counter({‘eggs‘: 1})
 2、python閉包

結論:盡量減少使用閉包

1、有的閉包可以使用兩個函數分開來寫,簡單易讀。

2、如果不使用nonlocal,可以讀取範圍外的變數,但是不能修改,使用nonlocal,可以讀取和修改,容易出bug,慎用!

3、python generators

要想建立一個iterator,必須實現一個有__iter__()和__next__()方法的類,類要能夠跟蹤內部狀態並且在沒有元素返回的時候引發StopIteration異常。

這個過程很繁瑣而且違反直覺,Generator能夠解決這個問題。

python generator是一個簡單的建立iterator的途徑,前面介紹那些繁瑣的步驟都可以被generator自動完成。

簡單來說,generator是一個能夠返回迭代器對象的函數。

python counter、閉包、generator

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.