gpt4 book ai didi

python - 如何对文件中的所有其他数字求和?

转载 作者:行者123 更新时间:2023-12-01 08:07:58 25 4
gpt4 key购买 nike

我需要在文件中创建每个其他数字的总和,如下所示:

10
20
30
40

只需将 20 和 40 加在一起即可得到 60。

try:
infile = open("numbers.txt", "r")

for lines in infile:
print(sum(infile))
infile.readline()[::2]

infile.close()

except ValueError:
print("Couldn't Open File")
except IOError:
print("File not found")

最佳答案

试试这个代码。

try:
with open("numbers.txt", "r") as infile:
print(sum([int(line) for line in infile][1::2]))
except ValueError:
print("Couldn't Open File")
except IOError:
print("File not found")

首先,它使用 with 构造来安全地处理文件的打开和关闭。其次,它使用列表理解来创建文件中的项目列表。第三,它使用 int() 将行从文本转换为整数。第四,它使用切片 [1::2] 来使用每隔一行,从第二行(索引为 1)开始。第五,它使用 sum 来添加这些数字。

说清楚了吗?如果您不喜欢列表理解,可以通过常规循环来完成。我的方法的主要缺点是它在只使用其中一半之前形成了所有项目的列表。下面是使用生成器删除该列表的代码,因此它使用更少的内存,但代价是更加复杂。

try:
with open("numbers.txt", "r") as infile:
print(sum(int(line) for ndx, line in enumerate(infile) if ndx % 2))
except ValueError:
print("Couldn't Open File")
except IOError:
print("File not found")

关于python - 如何对文件中的所有其他数字求和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55444168/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com