【发布时间】:2021-09-14 09:24:17
【问题描述】:
我是 Python 学习新手。 创建了一个包含一系列数字的 txt 文件: TXT 样式 A:1、3、4、2、22、11、...、32 TXT 样式 B:1 3 4 2 22...32 两个txt文件都可以打开。我未能添加值的总和。 问题一:带','的文字样式是否影响添加功能? 问题2:如何获取每个值并计算总和?
with open('numbers.txt', 'r') as f:
numbers_line = f.read()
print(numbers_line)
x = numbers_line.split()
#print(len(x))
定义数字():
i = len(x)
# Learn different methods to retrieve element
#s = int(x.__getitem__(25))
s = int(x[25])
w = int(x[24])
# Able to retrieve element, but this is not the way to program
# needed advice and corrections
print(i, s, w, s + w)
数字()
f.close()
【问题讨论】:
-
我有 numbers.txt 文件,包含从 1 到 32 的整数(有 25 个数字)
-
请澄清您的具体问题或提供更多详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。