You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中对同一矩阵的两列求和并添加结果列

How to Insert the Sum of Two Columns Between Them in a Python Matrix

Hey there! Let's tackle this problem where you need to take each row of a 2-column matrix, calculate the sum of the two elements, and insert that sum right between the original two values to form a new 3-column matrix.

Approach

The core idea is straightforward:

  • Iterate over each row in your original matrix
  • For each row, compute the sum of its two elements
  • Create a new row that combines the first original element, the sum, and the second original element
  • Collect all these new rows into a new matrix

Solution Code

First, here's a clear, step-by-step implementation using a basic loop:

# Your original input matrix
original_matrix = [[74, 25], [93, 76], [77, 41]]
new_matrix = []

for row in original_matrix:
    # Calculate the sum of the two elements in the current row
    row_sum = row[0] + row[1]
    # Build the new row with the sum inserted between the original values
    new_row = [row[0], row_sum, row[1]]
    # Add the new row to our result matrix
    new_matrix.append(new_row)

# Print the result to verify
print(new_matrix)

If you prefer a more concise (and Pythonic) way, you can use a list comprehension to achieve the same result in one line:

original_matrix = [[74, 25], [93, 76], [77, 41]]
new_matrix = [[x, x + y, y] for x, y in original_matrix]

print(new_matrix)

Output

Both implementations will produce your desired output:

[[74, 99, 25], [93, 169, 76], [77, 118, 41]]

Explanation

  • In the loop version: We initialize an empty list for our result, then loop through each row. For each row, we calculate the sum, build the new row structure, and add it to the result list.
  • In the list comprehension version: We unpack each row into variables x and y, then directly construct the new row by combining x, their sum x+y, and y—all in a single, readable line.

内容的提问来源于stack exchange,提问作者Abdullah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.01 02:19:06