在命令行执行时,应该有python3 a4.py apple
我试图求和的数字看起来与此完全相同
4 14
5
这是我到目前为止收集的内容
import sys
print(sys.argv[1])
fp = open(sys.argv[1])
fileContents = fp.read()
fp.close()
numbers = fileContents
print(numbers)
def map(f,items):
result = []
for i in range(0,len(items),1):
result = result + [f(items[i])]
return result
a=map(eval,numbers)
def sum(num):
total = 0
for i in range(0,len(num),1):
total = total + i
return total
print(sum(a))
答案 0 :(得分:4)
(我对“递归”标签感到有点困惑)
这个怎么样?
import sys
with open(sys.argv[1]) as inf:
total = 0
for line in inf:
total += sum(int(i) for i in line.split())
print(total)
备注:
float()
而不是int()
with
会在您完成或遇到执行时自动为您关闭文件。更新
您可以通过以下J.F.Sebastian的有用评论提供更多内容:
with open(sys.argv[1]) as inf:
print(sum(int(number) for line in inf for number in line.split()))
答案 1 :(得分:2)
我会根据你的例子使用Levon的解决方案。但是,如果您将数字格式化为货币或必须提取嵌入数字,则以下内容将作为基础:
import sys
import mmap
fin = open(sys.argv[1])
mm = mmap.mmap(fin.fileno(), 0, access=mmap.ACCESS_READ)
total = sum(int(m.group()) for m in re.finditer(r'\d+', mm))