python读取特定的线以计算



我有一个列表,其中有一个数字,其中我进行了一定的计算并完美地工作,该列表是文本文件; file.txt&quot',我有值(每行中一个(。在每个计算/检查中,我使用两行,其中有很多行,以下一个示例。

; file.txt;

73649
38761
34948
47653
98746
59375
90251
83661

...更多行/数字

在这种情况下,我将使用第1行和第2行进行第一次计算,我希望它使用第2和3行时,如果是错误的,则使用第3和4行,直到真实。

可以在Python中执行此操作?

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

(对于数百个兆字节的极大的文本文件来说,这不是很有效的(

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]

我想这个代码应该回答您的问题:

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函数返回的对。如果calculation的所有电话都返回false,则(a,b(被(无,无(

替换

另外,当数据流传输或不能完全存储在内存中时,您可以直接循环在流线上:

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

最新更新