for循环迭代变量的问题

时间:2020-02-03 10:44:42

标签: python python-3.x for-loop variables iteration

这是程序代码(缺少一些行): 这是从特定的字符串行中提取特定的数字,然后将这些数字一起算作一个浮点数,然后将它们除以在每个字符串中找到数字的次数。

问题是变量nc不包含在以下代码中?!

fname = "files/mbox-short.txt"
try:
    fh = open(fname)
except:
    print("No such a file, try again..")
    quit()


for lines in fh:
    if not lines.startswith("X-DSPAM-Confidence:"):
        continue
    oline = lines.split()


    for number in oline:
        nc = 0
        try:
            fnumber = float(number)
            nc = nc + 1
            print(fnumber, nc)
        except:
            continue

The file specified in the code

2 个答案:

答案 0 :(得分:0)

将nc = 0置于循环外,否则每次将其清零

答案 1 :(得分:0)

尝试:

nc = 0    
for number in oline:
    try:
        fnumber = float(number)
        nc = nc + 1
        print(fnumber, nc)
    except:
        continue