如何在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
xandy, then directly construct the new row by combiningx, their sumx+y, andy—all in a single, readable line.
内容的提问来源于stack exchange,提问作者Abdullah
相关产品推荐
相关产品推荐

