Python reduce

本文介绍了Python中reduce函数的应用,包括使用reduce函数实现列表求和、统计元素出现次数等常见任务。通过多种方法对比,如循环、递归及lambda表达式等方式,展示了reduce函数的强大与灵活性。

reduce函数:

def reduce(function, iterable, initializer=None):  
    it = iter(iterable)  
    if initializer is None:  
        try:  
            initializer = next(it)  
        except StopIteration:  
            raise TypeError('reduce() of empty sequence with no initial value')  
    accum_value = initializer  
    for x in iterable:  
        accum_value = function(accum_value, x)  
    return accum_value  

案例1:累加计算sum      list=[1,2,3,4,5]

# 方法1:用sum函数
sum(list)
# 方法2:循环方式
def customer_sum(lst):  
    result = 0  
    for x in lst:  
        result+=x  
    return result  

#或者  
def customer_sum(lst):  
    result = 0  
    while lst:  
            temp = lst.pop(0)  
            result+=temp  
    return result  

if __name__=="__main__":  
    lst = [1,2,3,4,5]  
    print customer_sum(lst)  
# 方法3:递归求和
def add(lst,result):  
    if lst:  
        temp = lst.pop(0)  
        temp+=result  
        return add(lst,temp)  
    else:  
        return result  

if __name__=="__main__":  
    lst = [1,2,3,4,5]  
    print add(lst,0) 
# 方法4:reduce方式
lst = [1,2,3,4,5]  
print reduce(lambda x,y:x+y,lst)  
#这种方式用lambda表示当做参数,因为没有提供reduce的第三个参数,所以第一次执行时x=1,y=2,第二次x=1+2,y=3,即列表的第三个元素  


#或者  
lst = [1,2,3,4,5]  
print reduce(lambda x,y:x+y,lst,0)  
#这种方式用lambda表示当做参数,因为指定了reduce的第三个参数为0,所以第一次执行时x=0,y=1,第二次x=0+1,y=2,即列表的第二个元素,  
假定指定reduce的第三个参数为100,那么第一次执行x=100,y仍然是遍历列表的元素,最后得到的结果为115  



#或者  
def add(x,y):  
    return x+y  

print reduce(add, lst)  
#与方式1相同,只不过把lambda表达式换成了自定义函数  

#或者  
def add(x,y):  
    return x+y  

print reduce(add, lst,0)  
#与方式2相同,只不过把lambda表达式换成了自定义函数

案例2:统计各个元素的个数      [1,1,2,3,2,3,3,5,6,7,7,6,5,5,5]

# 方法1:for循环判断
def statistics(lst):  
    dic = {}  
    for k in lst:  
        if not k in dic:  
            dic[k] = 1  
        else:  
            dic[k] +=1  
    return dic  

lst = [1,1,2,3,2,3,3,5,6,7,7,6,5,5,5]  
print(statistics(lst))  
# 方法2:set去重,count计数
def statistics2(lst):  
    m = set(lst)  
    dic = {}  
    for x in m:  
        dic[x] = lst.count(x)  

    return dic  

lst = [1,1,2,3,2,3,3,5,6,7,7,6,5,5,5]  
print statistics2(lst)  
# 方法3:reduce方式
def statistics(dic,k):  
    if not k in dic:  
        dic[k] = 1  
    else:  
        dic[k] +=1  
    return dic  

lst = [1,1,2,3,2,3,3,5,6,7,7,6,5,5,5]  
print reduce(statistics,lst,{})    
#提供第三个参数,第一次,初始字典为空,作为statistics的第一个参数,然后遍历lst,作为第二个参数,然后将返回的字典集合作为下一次的第一个参数  

或者  
d = {}  
d.extend(lst)  
print reduce(statistics,d)  
#不提供第三个参数,但是要在保证集合的第一个元素是一个字典对象,作为statistics的第一个参数,遍历集合依次作为第二个参数  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值