Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
218 views
in Technique[技术] by (71.8m points)

python sum function - `start` parameter explanation required

I am trying to understand the working of the built-in sum() function, but, the start parameter has evaporated my mind:

  1. a=[[1, 20], [2, 3]]
    b=[[[[[[1], 2], 3], 4], 5], 6]
    >>> sum(b,a)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: can only concatenate list (not "int") to list
    >>> sum(a,b)
    [[[[[[1], 2], 3], 4], 5], 6, 1, 20, 2, 3]
    
  2. >>> a=[1,2]
    >>> b=[3,4]
    >>> sum(a,b)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: can only concatenate list (not "int") to list
    >>> sum(b,a)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: can only concatenate list (not "int") to list
    

I am just dumbfounded by this and don't have any idea what is happening. Here is what the python docs have to say: http://docs.python.org/library/functions.html#sum. This does not give any explanation on 'what if the start is not a string and not an integer?'

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Sum does something like this

def sum(values, start = 0):
    total = start
    for value in values:
        total = total + value
    return total

sum([1,2],[3,4]) expands something like [3,4] + 1 + 2, which you can see tries to add numbers and lists together.

In order to use sum to produce lists, the values should be a list of lists, whereas start can be just a list. You'll see in your failing examples that the list contains at least some ints, rather then all lists.

The usual case where you might think of using sum with lists is to convert a list of lists into a list

sum([[1,2],[3,4]], []) == [1,2,3,4]

But really you shouldn't do that, as it'll be slow.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...