【问题标题】:Problem with the for loop iteration variable [closed]for循环迭代变量的问题[关闭]
【发布时间】:2020-05-19 02:43:34
【问题描述】:

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

问题是变量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

【问题讨论】:

  • nc=1for number in oline 循环内。
  • 您在 for 循环中的每次迭代都将 nc = 0 设置为 0。在 for 循环范围之外声明它

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


【解决方案1】:

尝试:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 哦,非常感谢,我实际上尝试将其从第二个循环中移出,但我仍然在第一个循环下,所以它不起作用,但在完全获取后它现在可以工作了在任何循环之外。
    猜你喜欢
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-27
    • 1970-01-01
    相关资源
    最近更新 更多