【问题标题】:Calculating with data from a txt file in python使用python中的txt文件中的数据进行计算
【发布时间】:2020-12-14 11:06:10
【问题描述】:

详细说明:

我在一个 txt 文件中有一组 200 个左右的值,我想选择第一个值 b[0],然后遍历从 [1] 到 [199] 的列表并将它们加在一起。

所以,[0]+[1]

如果不等于某个数字,那么它将进入下一个术语,即 [0]+[2] 等,直到它通过每个术语。完成后,它将 b[0] 增加到 b[1],然后再次遍历所有值

一步一步:

  1. 选择列表中的第一个数字。
  2. 将该号码添加到下一个号码
  3. 检查是否等于数字
  4. 如果没有,请转到下一个学期并添加到第一个学期
  5. 遍历这些直到您浏览完所有条款/找到 增加目标值的值
  6. 如果遍历所有值,则转到下一个术语 开始增值并继续

我无法让它工作,如果有人可以提供解决方案或提供一些建议吗?非常感激。我试过查看视频和其他堆栈溢出问题,但我仍然没有得到任何结果。也许我错过了什么,让我知道!谢谢! :)

我已经尝试过了,但被卡住了。到目前为止,这是我的代码:

b = open("data.txt", "r")
data_file = open("data.txt", "r")

for i, line in enumerate(data_file):
    if (i+b)>2020 or (i+b)<2020:
        b=b+1
    else:
        print(i+b)
        print(i*b)

错误:

Traceback (most recent call last):
  File "c:\Users\███\Desktop\ch1.py", line 11, in <module>
    if (i+b)>2020 or (i+b)<2020:
TypeError: unsupported operand type(s) for +: 'int' and '_io.TextIOWrapper'
PS C:\Users\███\Desktop>

【问题讨论】:

  • 你总结了索引i和文件对象b,看看b的声明
  • @BeliaevMaksim 嘿,谢谢你的回复,我不太清楚你的意思。我了解添加索引,但除此之外你失去了我
  • 你说b是文件:b = open("data.txt", "r")

标签: python list iteration txt


【解决方案1】:

我会将文件读入数组,然后将其转换为整数 实际处理问题。文件很乱,我们处理的越少越好

with open("data.txt", "r") as data_file:
    lines = data_file.readlines() # reads the file into an array
    data_file.close
j = 0 # you could use a better much more terse solution but this is easy to understand
for i in lines: 
    lines[j] = int(i.strip().replace("\n", ""))
    j += 1

i, j = 0
for i in lines: # for every value of i we go through every value of j
    # so it would do x = [0] + [0] , [0] + [1] ... [1] + [0] .....
    for j in lines:
        x = j + i
        if x == 2020:
            print(i * j)

【讨论】:

    【解决方案2】:

    您可以解决以下问题。

    您不能将文件对象 b 添加到整数 i。您必须使用以下方法将行转换为 int:

    integer_in_line = int(line.strip())
    

    您还以读取模式打开同一个文件两次:

    b = open("data.txt", "r")
    data_file = open("data.txt", "r")
    

    打开一次就够了。

    确保在使用后关闭文件:

    data_file.close()
    

    要将列表中的每个数字与列表中的其他数字进行比较,您需要使用双 for 循环。也许这对你有用:

    certain_number = 2020
    
    data_file = open("data.txt", "r")
    ints = [int(line.strip()) for line in data_file] # make a list of all integers in the file
    for i, number_at_i in enumerate(ints): # loop over every integer in the list
        for j, number_at_j in enumerate(ints): # loop over every integer in the list
            if number_at_i + number_at_j == certain_number: # compare the integers to your certain number
                print(f"{number_at_i} + {number_at_j} = {certain_number}")
    
    data_file.close()
    
    

    【讨论】:

      【解决方案3】:

      您的问题如下:变量bdata_file 实际上并不是您希望的文本。你应该阅读一些关于在 python 中读取文本文件的内容,有很多关于这方面的教程。

      当您调用open("path.txt", "r") 时,open 函数会返回一个文件对象,而不是您的文本。如果您想要文件中的文本,您应该调用readreadlines。阅读内容后关闭文件也很重要。

      data_file = open("data.txt", "r") # b is a file object
      text = data_file.read() # text is the actual text in the file in a single string
      data_file.close()
      

      或者,您也可以将文本读入字符串列表,其中每个字符串代表文件中的一行:lines = data_file.readlines()

      我假设您的“data.txt”文件每行包含一个数字,对吗?在这种情况下,您的 lines 变量将是一个数字列表,但它们将是字符串,而不是整数或浮点数。因此,您不能简单地使用它们来执行计算。你需要给他们打电话int()

      这是一个如何做到这一点的例子。我假设您的文本文件看起来像这样(带有任意数字):

      1
      2
      3
      4
      ... 
      
      file = open("data.txt", "r")
      lines = file.readlines()
      file.close()
      
      # This creates a new list where the numbers are actual numbers and not strings
      numbers = []
      for line in lines:
         numbers.append(int(line))
      
      target_number = 2020
      starting_index = 0
      
      found = False
      for i in range(starting_index, len(numbers)):
          temp = numbers[i]
          for j in range(i + 1, len(numbers)):
              temp += numbers[j]
              if temp == target_number:
                  print(f'Target number reached by adding nubmers from {i} to {j}')
                  found = True
                  break #This stops the inner loop.
          if found:
              break #This stops the outer loop
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-05-10
        • 2021-03-10
        • 1970-01-01
        • 1970-01-01
        • 2021-11-15
        • 2012-09-26
        • 1970-01-01
        • 2014-06-07
        相关资源
        最近更新 更多