简体   繁体   English

Python读取特定行以进行计算

[英]Python Read Specific Lines to Calc

I have a list with numbers where I make a certain calculation and works perfectly, the list is a text file "file.txt", in it I have values (one in each line).我有一个包含数字的列表,我可以在其中进行某些计算并完美运行,该列表是一个文本文件“file.txt”,其中我有值(每行一个)。 In each calculation / check I use two lines, there are many lines in it, an example follows.在每次计算/检查中我使用两行,其中有很多行,示例如下。

"file.txt" “文件.txt”

73649
38761
34948
47653
98746
59375
90251
83661

... more lines / numbers ...更多行/数字

In this case I would use line 1 and 2 for a first calculation, I would like it to be FALSE when it uses lines 2 and 3, in case of FALSE, use lines 3 and 4 until it is TRUE.在这种情况下,我将使用第 1 行和第 2 行进行第一次计算,当它使用第 2 行和第 3 行时,我希望它为 FALSE,在 FALSE 的情况下,使用第 3 行和第 4 行直到它为 TRUE。

Is it possible to do this in Python?可以在 Python 中做到这一点吗?

I guess that this code should answer your question:我想这段代码应该能回答你的问题:

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

When you leave the loop, (a,b) contains the pair for which the calculation function has returned True.当您离开循环时,(a,b) 包含calculation函数为其返回 True 的对。 If all calls to calculation have returned False, (a,b) is replaced by (None,None)如果对calculation所有调用都返回 False,则 (a,b) 替换为 (None,None)

Alternatively, when your data is streamed or cannot be totally stored in memory, you may directly loop over the stream lines:或者,当您的数据被流式传输或无法完全存储在内存中时,您可以直接循环遍历流线:

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

I think this answers your question:我认为这回答了你的问题:

(it won't be very efficient for extremely large text files over hundreds of megabytes) (对于超过数百兆字节的超大文本文件,效率不会很高)

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM