def sumx(): with open("C:\\Users\\ASUS\\Desktop\\student.txt", "r", encoding="UTF-8") as f: content=f.readlines() new = [content[i] for i in range(2,len(content),2)] new = [i[:-1] for i in new] new = [i.split() for i in new] new2 = list() for i in new: new1 = list() for j in range(2,len(i)): new1.append(int(i[j])) tmp = sum(new1) new2.append(tmp) with open("C:\\Users\\ASUS\\Desktop\\student.txt", "r", encoding="UTF-8") as f: content=f.readlines() header = content[0].split() a=int(input("请输入您的选择(1-3)")) data = [line.split() for line in content[1:]] data = data[1:] data.insert(-1,sumx) for i in data: print(i) data = list() 以上为函数以及程序代码 学号 姓名 语文 数学 外语 Python 221 董浩 95 75 80 80 222 罗邦楹 87 64 77 85 223 陈锦炜 75 85 66 76 224 陈天才 59 59 59 59 225 李松林 95 99 95 92 这个是文件的内容 请优化我的程序,使得求总分的数值能够每个人的成绩后面
时间: 2024-02-10 16:11:56 浏览: 72
13.DAX函数进阶篇(1)共8页.pdf.zip
你可以将函数sumx()中的最后一个for循环改为以下代码:
```
for i, row in enumerate(data):
row.append(str(new2[i]))
data[i] = row
```
这段代码可以将每个人的总分添加到其成绩后面,然后将修改后的data列表输出即可。最终的sumx()函数代码如下:
```
def sumx():
with open("C:\\Users\\ASUS\\Desktop\\student.txt", "r", encoding="UTF-8") as f:
content=f.readlines()
new = [content[i] for i in range(2,len(content),2)]
new = [i[:-1] for i in new]
new = [i.split() for i in new]
new2 = list()
for i in new:
new1 = list()
for j in range(2,len(i)):
new1.append(int(i[j]))
tmp = sum(new1)
new2.append(tmp)
with open("C:\\Users\\ASUS\\Desktop\\student.txt", "r", encoding="UTF-8") as f:
content=f.readlines()
header = content[0].split()
a=int(input("请输入您的选择(1-3)"))
data = [line.split() for line in content[1:]]
data = data[1:]
for i, row in enumerate(data):
row.append(str(new2[i]))
data[i] = row
for i in data:
print('\t'.join(i))
```
注意在输出时需要使用制表符('\t')将每个字段隔开。
阅读全文