Python counter, closures, generator

Source: Internet
Author: User

1. Python Library--counter
 fromCollectionsImportCounterbreakfast=['spam','spam','eggs','spam']breakfast_counter=Counter (breakfast) Breakfast_counter#Counter ({' Eggs ': 1, ' spam ': 3})#The function Most_common () returns all elements in descending order, or if given a number, returns the element before the numberBreakfast_counter.most_common ()#[(' Spam ', 3), (' Eggs ', 1)]Breakfast_counter.most_common (1)#[(' Spam ', 3)]#can combine counterslunch=['eggs','eggs','Bacon']lunch_counter=Counter (lunch) Lunch_counter#Counter ({' Bacon ': 1, ' Eggs ': 2})#the first way to combine counters is to use + from one counter plus anotherBreakfast_counter+lunch_counter#Counter ({' Bacon ': 1, ' eggs ': 3, ' spam ': 3})#the second way to combine counters is to use-remove another from one counterBreakfast_counter-lunch_counter#Counter ({' Spam ': 3})Lunch_counter-breakfast_counter#Counter ({' Bacon ': 1, ' Eggs ': 1})#the third way to combine counters is to use & to get the items that are common to bothBreakfast_counter&lunch_counter#Counter ({' Eggs ': 1})
2. Python closures

Conclusion: Minimizing the use of closures

1, some closures can use two functions to write separately, easy to read.

2, if you do not use nonlocal, you can read the variables outside the scope of the action, but can not be modified, using nonlocal, can read and modify, easy to make a bug, use with caution!

3. Python Generators

To create a iterator, you must implement a class with the __iter__ () and __next__ () methods that can track the internal state and throw a stopiteration exception when no element is returned.

The process is cumbersome and counterintuitive, and generator can solve the problem.

Python generator is a simple way to create iterator, and the tedious steps described above can be generator automatically.

In simple terms, generator is a function that returns an Iterator object.

Python counter, closures, generator

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.