找回密码
 立即注册

扫一扫,访问微社区

QQ登录

只需一步,快速开始

查看: 3642|回复: 1

[代码与实例] 小白求教 写的sum求和不能超过两个元素

1

主题

1

帖子

1

积分

贫民

积分
1
一个超人 发表于 2017-5-3 09:30:39 | 显示全部楼层 |阅读模式
1.     Write a function called list_total to calculate the sum of thelist of floating-point data type. Then use the function to calculate thefollowing list.
[12.5, 20.2,2.48, 4.5]
[3.3, 4.5, 2.6,2.8, 4.5]
[4, 4.5, 4.6,2.6]
List_total(alist)  
The return value is the sum of the alist
如何定义一个sum函数求和
回复

使用道具 举报

0

主题

3

帖子

3

积分

贫民

积分
3
GIL 发表于 2017-5-5 16:31:47 | 显示全部楼层
2个元素是什么意思 我没懂 所以给2个答案 不知道有没有你想要的
1:
def list_total(list):
    sum = 0
    for element in list:
        sum += element
    return sum


if __name__ == "__main__":
    alist = [12.5, 20.2, 2.48, 4.5]
    blist = [3.3, 4.5, 2.6, 2.8, 4.5]
    clist = [4, 4.5, 4.6, 2.6]
    alist_sum = list_total(alist)
    blist_sum = list_total(blist)
    clist_sum = list_total(clist)
    print alist_sum, blist_sum, clist_sum

2:
def list_total(alist):
    sum = 0
    for list in alist:
        for element in list:
            sum += element
    return sum


if __name__ == "__main__":
    alist = [12.5, 20.2, 2.48, 4.5]
    blist = [3.3, 4.5, 2.6, 2.8, 4.5]
    clist = [4, 4.5, 4.6, 2.6]
    print list_total([alist, blist, clist])
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表