if not(i % 2) and (i % 3)真假问题

2019-07-05  本文已影响0人  YoYoYoo

求100以内能被2整除却不能被3整除的数

>>> a = [i for i in range(100) if not (i % 2) and (i % 3)]
>>> a
[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]

Python中的真假测试对于整数而言,0为假,非0为真。
所以,这里的 not (i % 2) 为真的条件是:i % 2 为假,即 i % 2 == 0 ,即 i 能被 2 整除;i % 3 为真的条件是:i % 3 为非 0,即 i % 3 != 0,即 i 不能被 3 整除。

还有一个字典的小例子:

>>> b = {i:i % 2 == 0 for i in range(10)}
>>> b
{0: True, 1: False, 2: True, 3: False, 4: True, 5: False, 6: True, 7: False, 8: True, 9: False}
上一篇 下一篇

猜你喜欢

热点阅读