【问题标题】:Is the file style wrong? and how to adding the sum文件样式错了吗?以及如何添加总和
【发布时间】: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 个数字)
  • 请澄清您的具体问题或提供更多详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。

标签: sum element add


【解决方案1】:

带有','的文字样式是否影响添加功能?

在我们开始添加之前,它确实会影响拆分,因为str.split() 如果没有指定分隔符,只会在空格处拆分。要在逗号和空格处拆分,您可以

import re
…
    x = re.split("[,\s]+", numbers_line)

如何获取每个值并计算总和?

您已经使用 int 函数将字符串转换为整数(尽管使用 int(x[25]) 您错过了索引范围从 0 到 24);您可以使用map 函数将int 应用于x 的每个字符串,并且可以使用sum 函数计算总和:

    print(sum(map(int, x)))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-24
    相关资源
    最近更新 更多