我正在编写一个代码,该代码应该包含文件名并创建一个初始列表。然后,我试图总结列表中的每个项目。到目前为止我写的代码看起来像这样......
filename = input('Enter filename: ')
Lists = []
for line in open(filename):
line = line.strip().split()
Lists = line
print(Lists)
total = 0
for i in Lists:
total = sum(int(Lists[i]))
print(total)
我接受一个文件名并将line =中的所有对象设置为List。然后,我创建一个变量total,它应该打印出列表中每个项目的总和。例如,如果List = [1,2,3]则总数将为6.但是,是否可以将整数对象附加到列表中?我收到的错误是......
File "/Users/sps329/Desktop/testss copy 2.py", line 10, in main
total = sum(int(Lists[i]))
TypeError: list indices must be integers, not str
这样的东西也不起作用,因为List中的项目是字符串而不是数字。我是否必须实现函数isdigit,即使我知道输入文件将始终是整数?...
total = sum(i)
答案 0 :(得分:5)
而不是
Lists = line
你需要
Lists.append(line)
你可以得到这样的总和
total = sum(sum(map(int, item)) for item in Lists)
如果您不想创建列表列表,可以使用extend
函数
Lists.extend(line)
...
total = sum(map(int, Lists))
答案 1 :(得分:2)
# creates a list of the lines in the file and closes the file
with open(filename) as f:
Lists = f.readlines()
# just in case, perhaps not necessary
Lists = [i.strip() for i in Lists]
# convert all elements of Lists to ints
int_list = [int(i) for i in Lists]
# sum elements of Lists
total = sum(int_list)
答案 2 :(得分:1)
print sum([float(x.strip()) for x in open(filename)])