Python 内置函数 filter map reduce

本文介绍了如何使用Python的filter和map函数来筛选素数,并提供了这些内置函数的自定义实现。同时,展示了reduce函数及其Python实现,用于简化数据处理任务。文章通过实例深入探讨了Python中函数式编程的概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

def is_prime_num(num):
    if num <=3:
        return False
    for n in xrange(2, num):
        if num%n == 0:
            return False
    return True
# 找出1到100的素数
a = range(1, 100) 
f = filter(is_prime_num, a)
print f

 

 

# filter内建函数的python实现
def filter(bool_func,seq):
	filtered_seq = []
	for eachItem in seq:
		if bool_func(eachItem):
			filtered_seq.append(eachItem)
	return filtered_seq

 

 

>>> map(lambda x : None,[1,2,3,4])
[None, None, None, None]
>>> map(lambda x : x * 2,[1,2,3,4])
[2, 4, 6, 8]
>>> map(lambda x : x * 2,[1,2,3,4,[5,6,7]])
[2, 4, 6, 8, [5, 6, 7, 5, 6, 7]]
>>> map(lambda x : None,[1,2,3,4])
[None, None, None, None]


#  map内建函数的python实现:
def map(func,seq):
	mapped_seq = []
	for eachItem in seq:
		mapped_seq.append(func(eachItem))
	return mapped_seq

 

 

 

>>> reduce(lambda x,y : x + y,[1,2,3,4])
10
>>> reduce(lambda x,y : x + y,[1,2,3,4],10)
20

#  reduce的python实现: 
def reduce(bin_func,seq,initial=None):
	lseq = list(seq)
	if initial is None:
		res = lseq.pop(0)
	else:
		res = initial
	for eachItem in lseq:
		res = bin_func(res,eachItem)
	return res

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值