如何检查文本文件中的下一个元素是否比前一个元素多1个?

时间:2014-10-01 04:29:14

标签: python python-3.x

我有一个编程功课问题: 创建脚本以检查文本文件中的下一个元素是否等于前一个加1并报告文本文件中不符合此条件的行的好方法是什么?

文本文件如下:

1
3
2
4

到目前为止我所拥有的:

filename=input('filename')
easy_text_file = open(filename, "rU")
store=1
count=0
for entry in easy_text_file:
    entry_without_newline = entry[:-1]
    data_list=list(entry_without_newline)
if store != data_list[0]:
    print(store)
    print(data_list[0])
    count=count+1
    print('This line does not satisfy the condition at line: ',count)
    break
store=data_list[0]
print(store)
count=count+1

如果我将文本文件编辑为:

1
2
3
4
6
5

它仍然返回“此行不满足行的条件:1”

4 个答案:

答案 0 :(得分:2)

看起来,你只需要跟踪两条连续的线并检查线对的条件 - > 1-2 2-3 3-4 4-5 ... 这段代码工作正常,我只是读一行并保持前一行的轨迹。

x=True
count=0
f=open("text.txt")
for line in f:
    if (x==True):   #This condition will be true just once.(for first line only)
        prevline=line
        line = f.next() #reading the second line. I will save this line as previous line. 
        x=False
a=int(prevline) #typecasting
b=int(line)
a=a+1
if(a!=b):
    print "this line does not satisfy the condition at line:",count
prevline=line #keeping the track of previous line
count=count+1
f.close()

答案 1 :(得分:1)

在进入循环之前读取文件的第一行。这将允许您初始化预期的序列,而不假设文件中的第一个数字是1。

初始化后,只需跟踪下一行所需的值,从文件中读取一行,将其转换为整数,将其与预期值进行比较,如果值不符合则打印错误消息同意。

您不需要将每一行转换为列表,只需使用int() - 它也会忽略换行符。您还应处理非数字数据 - int()如果无法将该行转换为有效整数,则会引发ValueError

此外,您可以使用计数器(根据您的代码)或使用enumerate()跟踪行号。

将所有这些放在一起你可能会像这样编码:

filename = input('filename')
with open(filename, 'rU') as easy_text_file:
    expected = int(next(easy_text_file)) + 1    # initialise next line from first line

    for line_number, entry in enumerate(easy_text_file, 2):
        try:
            entry = int(entry)
            if entry != expected:
                print("Line number {} does not satisfy the condition: expected {}, got {!r}".format(line_number, expected, entry))
            expected = entry + 1
        except ValueError:
            print("Line number {} does not contain a valid integer: {!r}".format(line_number, entry)

答案 2 :(得分:1)

  • 构建生成器以将每一行作为int
  • 返回
  • 阅读第一行,并构建一个产生预期值的计数器
  • 比较每个值和期望值
  • 如果不同,请打印行号,值和预期值并中断
  • 没有发生休息的地方(与else相关联的for) - 打印所有商品

例如:

from itertools import count

with open('testing.txt') as fin:
    lineno = 0
    lines = map(int, fin)
    try:
        expected = count(next(lines) + 1)
        for lineno, (fst, snd) in enumerate(zip(lines, expected), 2):
            if fst != snd:
                print('problem on line {}: got {}, expected {}'.format(lineno, fst, snd))
                break
        else:
            print('All was fine')
    except StopIteration:
        print('File was empty')
    except ValueError as e:
        print('Error converting line {} - {}'.format(lineno + 1, e))

答案 3 :(得分:0)

另一种选择:

easy_text_file = open("number.txt", "rU")

#directly iterate each line of easy_text_file, convert it to int and create list
initial = [int(line) for line in easy_text_file]

#Based your requirement : next value should be equal to previous + 1
#So we create list with starting point from first value to length of initial list 
compare = range(initial[0], len(initial)+1)

#Using zip function to create a match tuple between those list
#Output of zip(initial, compare) => [(1,1),(2,2),(3,3),(5,4), ....]
#Then we compare between each values
for i, j in zip(initial, compare):
    if i!=j:
        print 'This line does not satisfy the condition at line: ', j
        break

easy_text_file.close()

结果:

>>> 
This line does not satisfy the condition at line:  4
>>> initial
[1, 2, 3, 5, 5, 3, 5]
>>> compare
[1, 2, 3, 4, 5, 6, 7]
>>>