程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Pythons true and false test performs mathematical screening on data

編輯:Python

This is an article in Python Notes in learning .
May we make progress together .

Problem description

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 .

True and false test

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 .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved