简体   繁体   中英

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). In each calculation / check I use two lines, there are many lines in it, an example follows.

"file.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.

Is it possible to do this in 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. If all calls to calculation have returned False, (a,b) is replaced by (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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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