Hướng dẫn python sum tuples elementwise

Zip them, then sum each tuple.

[sum[x] for x in zip[a,b]]

EDIT : Here's a better, albeit more complex version that allows for weighting.

from itertools import starmap, islice, izip

a = [1, 2, 3]
b = [3, 4, 5]
w = [0.5, 1.5] # weights => a*0.5 + b*1.5

products = [m for m in starmap[lambda i,j:i*j, [y for x in zip[a,b] for y in zip[x,w]]]]

sums = [sum[x] for x in izip[*[islice[products, i, None, 2] for i in range[2]]]]

print sums # should be [5.0, 7.0, 9.0]

Sum list of tuples element-wise in Python #

To sum a list of tuples element-wise:

  1. Use the zip function to get an iterator of tuples with the corresponding items.
  2. Use a list comprehension to iterate over the iterable.
  3. On each iteration, pass the tuple to the sum[] function.

Copied!

list_of_tuples = [[1, 2], [3, 4], [5, 6]] # 👇️ [[1, 3, 5], [2, 4, 6]] print[list[zip[*list_of_tuples]]] result = [sum[tup] for tup in zip[*list_of_tuples]] print[result] # 👉️ [9, 12]

The zip function iterates over several iterables in parallel and produces tuples with an item from each iterable.

Copied!

list_of_tuples = [[1, 2], [3, 4], [5, 6]] # 👇️ [[1, 3, 5], [2, 4, 6]] print[list[zip[*list_of_tuples]]]

We used the * iterable unpacking operator to unpack the tuples in the call to the zip[] function.

Copied!

list_of_tuples = [[1, 2], [3, 4], [5, 6]] # 👇️ [1, 2] [3, 4] [5, 6] print[*list_of_tuples]

The * iterable unpacking operator enables us to unpack an iterable in function calls, in comprehensions and in generator expressions.

You can imagine that the zip[] function iterates over the tuples, taking 1 item from each.

Copied!

list_of_tuples = [[1, 2], [3, 4], [5, 6]] # 👇️ [[1, 3, 5], [2, 4, 6]] print[list[zip[*list_of_tuples]]]

The first tuple in the list consists of the elements in each tuple that have an index of 0, and the second tuple consists of the elements in each tuple that have an index of 1.

The last step is to use a list comprehension to iterate over the zip object and sum each tuple.

Copied!

list_of_tuples = [[1, 2], [3, 4], [5, 6]] # 👇️ [[1, 3, 5], [2, 4, 6]] print[list[zip[*list_of_tuples]]] result = [sum[tup] for tup in zip[*list_of_tuples]] print[result] # 👉️ [9, 12]

List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

The sum function takes an iterable, sums its items from left to right and returns the total.

On each iteration, we pass the current tuple to the sum[] function and get the total.

You can use this approach with a list that stores tuples of arbitrary length.

Copied!

list_of_tuples = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # 👇️ [[1, 4, 7], [2, 5, 8], [3, 6, 9]] print[list[zip[*list_of_tuples]]] result = [sum[tup] for tup in zip[*list_of_tuples]] print[result] # 👉️ [12, 15, 18]

Chủ Đề