过滤奇数:
def odd(n): return n % 2 == 1 list(filter(is_odd, [1, 2, 3,4,5,6,7,8]))此处将filter换成map,可以看出map和filter的区别
过滤空格:def not_empty(s):
return s and s.strip()
list(filter(not_empty, ['A', '', 'B', None, 'C', ' ']))过滤1000以内素数:def shengchengqi():
n = 1
while True:
n = n + 2
yield n
def shaixuanqi():
return lambda x : x % n > 0
def fanhuisushu():
yield 2
it = shengchengqi()
while True:
n = next(it)
yield n
it = filter(shaixuanqi(n),it)
for n in fanhuisushu():
if n < 1000:
print(n)
else:
break
本文介绍了使用Python实现的几个实用函数,包括过滤列表中的奇数、去除字符串中的空格以及生成1000以内的素数。通过定义生成器和筛选器,展示了Python在处理数学问题上的灵活性。
841

被折叠的 条评论
为什么被折叠?



