This is an article in Python Notes in learning .
May we make progress together .
When writing a function, it will endlessly calculate a series of numbers that meet the expression .
These numbers occupy our memory crazily .
Don't panic at this time , First Ctrl+C Stop the program .
Want to have a filter like method to leave useful numbers , Useless elimination .
Python The true and false test of is to judge whether the condition is true or false ,0 For false , except 0 An integer other than is true .
Take a chestnut 》》》
>>> a=[i for i in range(100) if not(i%2) and (i%3)]
>>> a
The result is zero :[2, 4, 8, 10, 14, 16, 20, 22, 26, 28, 32, 34, 38, 40, 44, 46, 50, 52, 56, 58, 62, 64, 68, 70, 74, 76, 80, 82, 86, 88, 92, 94, 98]
It can be seen that , The effect of the above list generation formula is to filter (0,100) Even number in .
thus , Analyzing expressions is much simpler .
if # In judgment , Only True Operation in case of , Therefore, the following needs to be true
and # And operation , Both sides of the binomial operator are true
not(i%2) and (i%3) all True
not(i%2) == 1 # namely i%2 == 0
i%3 == 1 # namely i%3 != 0
Sum up , Expressed as i Can be 2 to be divisible by , Can't be 3 to be divisible by , Screen even numbers .
Another chestnut :
>>> b = {
i: i%2 == 0 for i in range(10)}
>>> b
The result is :
{0: True, 1: False, 2: True, 3: False, 4: True, 5: False, 6: True, 7: False, 8: True, 9: False}
Generated here as a dictionary .
One 、 Introduction to credit r
After writing the interface wi