質問

I have this this list of tuple:

  a = [(1, 2), (1, 4), (1, 6)]

I would like to use the reduce function in order to get this result:

  (3, 12)

I tried:

  x = reduce(lambda x, y: x+y, a)

But i get an error...I want to add up all the elements in the first index of each tuple, then add up the second element.

役に立ちましたか?

解決

If you want the output of a reduce to be a tuple, all the intermediate results should also be a tuple.

a = [(1, 2), (1, 4), (1, 6)]
print reduce(lambda x, y: (x[0] + y[0], x[1] + y[1]), a)

Output

(3, 12)

Edit: If you want to get (0, 0) when the list is empty

a = []
print reduce(lambda x, y: (x[0] + y[0], x[1] + y[1]), [(0, 0)] + a)

Output

(0, 0)

Edit 2: Reduce accepts default initializer as the last parameter, which is optional. By using that, the code becomes

a = []
print reduce(lambda x, y: (x[0] + y[0], x[1] + y[1]), a, (0, 0))

他のヒント

>>> a = [(1, 2), (1, 4), (1, 6)]
>>> map(sum, zip(*a))
[3, 12]

UPDATE

According to Raymond Hettinger,

zip-star trick abuses the stack to expensively compute a transpose.

Here's an alternative that does not use list comprehension.

>>> a = [(1, 2), (1, 4), (1, 6)]
>>> [sum(item[i] for item in a) for i in range(2)] # 2 == len(a[0])
[3, 12]
>>> a = []
>>> [sum(item[i] for item in a) for i in range(2)] # 2 == len(a[0])
[0, 0]

You were close. Just modify your code to unpack the input tuples first. Once you add the new values, just repack the result tuple:

>>> a = [(1, 2), (1, 4), (1, 6)]
>>> reduce(lambda (sx, sy), (x, y): (sx+x, sy+y), a)
(3, 12)

Try this:

>>> from numpy import asarray
>>> a = asarray([(1, 2), (1, 4), (1, 6)])
>>> reduce(lambda x,y:x+y, a)
array([ 3, 12])
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top