读取文件中的行数未知

时间:2019-12-27 16:10:07

标签: python python-3.x

我写了下面的代码,但是它指定了文件中的行数。我想知道如何更改它,以使其读取未知数量的行?

n = int(input("instance: "))
tp, tn, fp, fn = 0
for i in range(n):
    real, predicted = map(int, input().split(' '))
    for num in i:
        if real == 1 and predicted == 1:
            tp += 1
        elif real == 0 and predicted == 0:
            tn += 1
        elif real == 1 and predicted == 0:
            fn += 1
        else:
            fp += 1

pr = tp / (tp + fp)
rc = tp / (tp + fn)
f1 = 2 * ((pr * rc) / (pr + rc))
print("f1= ", f1)

我的代码读取这些行,并将每行中的数字相互比较,但不与其他行中的数字进行比较。

输入看起来像这样:

1 1
0 0
0 1
0 1
1 0
0 1
0 0
1 1
0 0
0 0
0 0
0 0
1 1

1 个答案:

答案 0 :(得分:2)

保持阅读,直到抛出EOFError

tp, tn, fp, fn = 0
i = 0
try:
    while True:
        real, predicted = map(int, input().split(' '))
        for num in i:
            if real == 1 and predicted == 1:
                tp += 1
            elif real == 0 and predicted == 0:
                tn += 1
            elif real == 1 and predicted == 0:
                fn += 1
            else:
                fp += 1
        i += 1
except EOFError:
    pass
pr = tp / (tp + fp)
rc = tp / (tp + fn)
f1 = 2 * ((pr * rc) / (pr + rc))
print("f1= ", f1)

您的代码也有错误:

  • 无法使用拆包将多个变量分配给相同的值。
  • 如果您要计算一个数字,则需要使用
  • range

这应该解决它们:

tp = tn = fp = fn = 0
i = 0
try:
    while True:
        real, predicted = map(int, input().split(' '))
        for num in range(i):
            if real == 1 and predicted == 1:
                tp += 1
            elif real == 0 and predicted == 0:
                tn += 1
            elif real == 1 and predicted == 0:
                fn += 1
            else:
                fp += 1
        i += 1
except EOFError:
    pass
pr = tp / (tp + fp)
rc = tp / (tp + fn)
f1 = 2 * ((pr * rc) / (pr + rc))
print("f1= ", f1)