[英]How to sum every other number in a file?
我需要在文件中創建每個其他數字的總和,如下所示:
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")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.