返回信息流如图,求大神给普及一下sum函数用法,具体问题就是上边例子中参数“[]”的作用,跪谢!
这是一条镜像帖。来源:北邮人论坛 / python / #2884同步于 2014/8/13
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Python机器人发帖
[问题]sum函数,参数“[]”
wai7niu8
2014/8/13镜像同步7 回复
订阅后,新回复会通过你的通知中心匿名送达。
7 条回复
sum(iterable[, start]), 第二个参数是可选的
【 在 wai7niu8 的大作中提到: 】
: [upload=1][/upload]
: 如图,求大神给普及一下sum函数用法,具体问题就是上边例子中参数“[]”的作用,跪谢!
sum(...)
sum(sequence[, start]) -> value
Return the sum of a sequence of numbers (NOT strings) plus the value
of parameter 'start' (which defaults to 0). When the sequence is
empty, return start.
>>> lst1 = [['hello'],['world']]
>>> sum(lst1,['a','b','c'])
['a', 'b', 'c', 'hello', 'world']
>>> lst2 = ['hello','kitty']
>>> sum(lst1,lst2)
['hello', 'kitty', 'hello', 'world']
>>>
你的那个 就相当于 加了一个空 []
既然是可选的,为什么不加就会报错捏~
【 在 yangnick 的大作中提到: 】
: sum(iterable[, start]), 第二个参数是可选的
给解释一下后半部分为什么报错吧~[ema23]
【 在 wangxiaobupt 的大作中提到: 】
: sum(...)
: sum(sequence[, start]) -> value
: Return the sum of a sequence of numbers (NOT strings) plus the value
: ...................
sum(sequence[, start]) -> value
Returns the sum of a sequence of numbers (NOT strings) plus the value
of parameter 'start' (which defaults to 0). When the sequence is
empty, returns start.
第二个参数为start,默认为0。将0与list相加当然会报错
好吧 翻译一下
sum函数:
先求一个list(第一个参数)的和再加上(可有可无)的参数start的值(默认为0)
如果没有第二个参数 那相当于 你list内两个相加 在加上0
【 在 wai7niu8 (wai7niu8) 的大作中提到: 】
: 给解释一下后半部分为什么报错吧~[ema23]
python报错已经解释的很清楚了,sum接受一个参数的时候,会将该list的全部元素作为整数求和,而你的a的两个元素是list,于是有报错:unsupported operand type(s) for +: 'int' and 'list'
【 在 wai7niu8 的大作中提到: 】
: 给解释一下后半部分为什么报错吧~