Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

sum - Summing non-integers in Python

Is it possible to take the sum of non-integers in Python?

I tried the command

sum([[1], [2]])

to get [1, 2], but it gives the error

Traceback (most recent call last):
  File "<pyshell#28>", line 1, in <module>
    sum([[1], [2]])
TypeError: unsupported operand type(s) for +: 'int' and 'list'

I suspect sum tries to add 0 to the list [1], resulting in failure. I'm sure there are many hacks to work around this limitation (wrapping stuff in a class, and implementing __radd__ manually), but is there a more elegant way to do this?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

It looks like you want this:

>>> sum([[1],[2]], [])
[1, 2]

You're right that it's trying to add 0 to [1] and getting an error. The solution is to give sum an extra parameter giving the start value, which for you would be the empty list.

Edit: As gnibbler says, though, sum is not a good way to concatenate things. And if you just want to aggregate a sequence of things, you should probably use reduce rather than make your own __radd__ function just to use sum. Here's an example (with the same poor behavior as sum):

>>> reduce(lambda x, y: x+y, [[1],[2]])
[1, 2]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...