【问题标题】:Python Read Specific Lines to CalcPython 将特定行读取到 Calc
【发布时间】:2018-04-22 23:48:19
【问题描述】:

我有一个带有数字的列表,我在其中进行了一定的计算并且运行良好,该列表是一个文本文件“file.txt”,其中我有值(每行一个)。在每个计算/检查中我使用两行,其中有很多行,下面是一个示例。

“文件.txt”

73649
38761
34948
47653
98746
59375
90251
83661

...更多行/数字

在这种情况下,我将使用第 1 行和第 2 行进行第一次计算,当它使用第 2 行和第 3 行时,我希望它为 FALSE,如果为 FALSE,请使用第 3 行和第 4 行,直到它为 TRUE。

在 Python 中可以做到这一点吗?

【问题讨论】:

  • 您的意思是要创建一个结构,其中您的数字按 2 2 分组,以便您可以对每一对进行计算?
  • 是的!!!我将使用第 1 行和第 2 行,如果是 FALSE,我将使用第 2 和 3 行,如果是 FALSE,我将使用第 3 和 4 行,依此类推,直到找到 TRUE。谢谢
  • 是的,这在 Python 中是可能的。你的问题到底是什么?是读取数字还是配对?你知道 Python 的zip 函数吗?你需要在你的问题中展示更多的工作和更多的背景。

标签: python


【解决方案1】:

我认为这回答了你的问题:

(对于超过数百兆字节的超大文本文件效率不高)

def calc(x, y):

    # do your calculation here



file = open("file.txt", "r")

list = file.readlines()

file.close()

item = 0

while item < len(list) - 1:

    if calc(list[item], list[item + 1]) == false:

        item += 1

# once you have found the lines that output false, you can do whatever you 
# want with them with list[item] and list[item + 1]

【讨论】:

    【解决方案2】:

    我猜这段代码应该能回答你的问题:

    lst = [int(line) for line in open('bar.txt','r')]
    
    for n in range(len(lst)-1):
        a, b = lst[n], lst[n+1]
        if calculation(a,b): break
    else:
        a, b = None, None
    

    当您离开循环时,(a,b) 包含 calculation 函数为其返回 True 的对。如果对 calculation 的所有调用都返回 False,则 (a,b) 将替换为 (None,None)

    或者,当您的数据被流式传输或无法完全存储在内存中时,您可以直接循环流线:

    with open('bar.txt', 'r') as file:
        a = None
        for b in file:
            b = int(b)
            if a != None and calculation(a,b): break
            a = b
        else:
            a, b = None, None
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-28
      相关资源
      最近更新 更多