2 回答
TA贡献1830条经验 获得超3个赞
这是代码重写的示例,我认为它演示了您所要求的内容:
fyle = input('Enter the file name you want to process: ')
def read_data(fyle):
lne = [line.strip().split() for line in open(fyle).readlines()]
newlist = [[elem[1], elem[0], elem[2]] for elem in lne]
return newlist
def compute_sum(newlist):
s = sum([int(x[0]) for x in newlist])
return s
list = read_data(fyle)
sum = compute_sum(list)
print(sum)
数据文件/tmp/data.txt:
line1_item1 10 line1_item3
line2_item1 20 line2_item3
line3_item1 30 line3_item3
结果:
Enter the file name you want to process: /tmp/data.txt
60
TA贡献1757条经验 获得超8个赞
下面的代码应该可以计算总和。正如您在上面的帖子中提到的,我考虑过 mylist = [[Smith, Bob, 18], [Jorgen, Peter, 14]]。
def compute_sum(new_list):
sum=0
for item in new_list:
sum=sum+int(item[2])
#print(sum)
return sum
添加回答
举报