Python读取文件后实现两列数值逐行相加的方法
Hey there! Let's work through how to get those two columns of numbers added up in Python. First, I noticed a small detail: your start list has 7 values, but summit has 8—probably a typo when you shared the data. I'll cover scenarios for both matching lengths and the mismatched case, plus how to handle this if your data is stored in a file (since you mentioned needing to read a file for your school project).
方法1:基础Python(直接处理列表数据)
If you already have the data in Python lists (like you shared), you can use a simple list comprehension or loop to pair and add the values.
匹配长度的情况(修正数据后)
First, let's align the lengths of the two lists (I'll remove the extra 158 from summit to match start):
start = [713866, 936003, 937328, 968012, 1004680, 1167304, 1209211] summit = [207, 263, 46, 459, 61, 154, 180] # 用列表推导式快速生成相加结果 total_list = [s + sm for s, sm in zip(start, summit)] # 打印每一行的结果 for row_num, total in enumerate(total_list, start=1): print(f"第{row_num}行: {start[row_num-1]} + {summit[row_num-1]} = {total}")
处理长度不一致的情况
If that extra 158 in summit is intentional, you can use itertools.zip_longest to handle the mismatch. This will fill missing values with a default (like 0) so every value gets added:
from itertools import zip_longest start = [713866, 936003, 937328, 968012, 1004680, 1167304, 1209211] summit = [207, 263, 46, 459, 61, 154, 180, 158] total_list = [] for s, sm in zip_longest(start, summit, fillvalue=0): total = s + sm total_list.append(total) print(f"{s} + {sm} = {total}")
方法2:读取文件并计算(适合项目场景)
Since you mentioned needing to read a file for your school project, let's cover two common file types: CSV and plain text.
场景A:CSV文件
CSV is super common for tabular data. We'll use pandas (a popular data analysis library) because it makes this trivial.
First, install pandas if you haven't already:
pip install pandas
Suppose your CSV file (data.csv) looks like this:
start,summit 713866,207 936003,263 937328,46 968012,459 1004680,61 1167304,154 1209211,180
Here's the code to read it, add the columns, and save the result:
import pandas as pd # 读取CSV文件 df = pd.read_csv("data.csv") # 新增一列存储相加结果 df["total"] = df["start"] + df["summit"] # 打印结果到控制台 print(df) # 保存结果到新的CSV文件(可选) df.to_csv("calculated_results.csv", index=False)
场景B:纯文本文件(每行两个数值)
If your file is a plain text file (data.txt) with one pair of numbers per line:
start summit 713866 207 936003 263 937328 46 968012 459 1004680 61 1167304 154 1209211 180
You can use basic file handling to read and calculate:
total_list = [] # 打开文件并逐行处理 with open("data.txt", "r") as file: # 跳过表头行 next(file) for line in file: # 分割每行的两个数值,转换为整数 start_val, summit_val = map(int, line.strip().split()) total = start_val + summit_val total_list.append(total) print(f"{start_val} + {summit_val} = {total}") # 如果需要保存结果到文件 with open("results.txt", "w") as output_file: output_file.write("start + summit = total\n") for idx, total in enumerate(total_list, start=1): output_file.write(f"{start[idx-1]} + {summit[idx-1]} = {total}\n")
All these methods should get you the逐行相加 results you need for your project. Let me know if you run into any snags with your specific file format!
内容的提问来源于stack exchange,提问作者M.Greene

