"Python" Programming Learning exercises-2

Source: Internet
Author: User

Tag: the sum () function provided by Python can accept a list and sum please write a prod () function to accept a list and use the reduce () to calculate the product:

1 #Python提供的sum () function can accept a list and sum, write a prod () function, you can accept a list and use reduce () to calculate the product:


Code:


2 3 from Functools import reduce 4 Li = [1,2,3,4,5,7] 5 print (sum (LI)) 6 7 def prod (x, y): 8 return x * y 9 Ten R = Reduce (Prod,li) one print (R)


Operation Result:


[[email protected] practice]# python map_reduce_2.py 22840[[email protected] practice]#


Code Explanation:


  2   3 from functools import reduce              #导入reduce模块   4 li = [1,2,3,4,5,7]                         #创建一个列表用于计算   5 print (sum (LI))                              #打印求和结果   6   7 def prod (x, y):                             #定义函数prod, pass in two parameters x,y  8     return x * y                           #返回xProduct of Y and   9  10 r = reduce (prod,li)                        #reduce   Incoming functions prod and list li  11 print (R)                                  # Print results


This article is from the "Learning Notes" blog, so be sure to keep this source http://netsyscode.blog.51cto.com/6965131/1751356

"Python" Programming Learning exercises-2

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.