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