开发者

Sum numbers in an array

开发者 https://www.devze.com 2023-01-15 11:48 出处:网络
I\'m a Python newbie. At this site, they sh开发者_开发问答ow how to sum list of integers. What if instead of a list of raw ints, you had a list of

I'm a Python newbie.

At this site, they sh开发者_开发问答ow how to sum list of integers.

What if instead of a list of raw ints, you had a list of

class Number :
   def __init__( self, x = 0) :
      self.number = x      

   def getNumber( self ) :
      return self.number

What's the Python code to sum the self.number in an array in a few lines (hopefully)?


I am assuming you mean a list or maybe another kind of iterable:

sum(x.getNumber() for x in L)


Try this:

sum(x.getNumber() for x in l)

By the way, [1, 2, 3]is a list, not an array.


Use a generator or list comprehension:

numbers = [Number(1), Number(2)]
sum(n.getNumber() for n in numbers)

Simply, it calls the method getNumber() on each item before summing.


Here are several ways to do it:

sum( e.getNumber() for e in L )

sum( e.number for e in L )

reduce( lambda a,b: a + b.getNumber(), L, 0 )  # likewise for e.number
0

精彩评论

暂无评论...
验证码 换一张
取 消