一行代码求出100以内为3倍数的所有数

# method 1
print(list(filter(lambda n: not (n % 3), range(1, 100))))

# method 2
print(list(filter(lambda x: x % 3 == 0, range(1, 100))))

filter函数lambda函数这里不做过多解释,总而言之它会返回值为True的情况。n%3会得到三种结果,0,1,2,我们知道在python中0代表False,任何不为0的数字代表True,因此当n%3==0的时,not (n%3) != 0,因此此时会返回对应的迭代值,method 2中的代码也可以实现相同的效果,对method 1算是一种解释。

猜你喜欢

转载自blog.csdn.net/u011699626/article/details/107964233