【问题标题】:else statement does not return to loopelse 语句不返回循环
【发布时间】:2015-03-22 05:12:37
【问题描述】:

我有一个代码可以打开一个文件,计算中间值并将该值写入一个单独的文件。有些文件可能是空的,所以我编写了以下循环来检查文件是否为空,如果是,则跳过它,增加计数并返回循环。它完成了它找到的第一个空文件的预期,但不是第二个。循环如下

t = 15.2
while t>=11.4:
 if os.stat(r'C:\Users\Khary\Documents\bin%.2f.txt'%t ).st_size > 0:  
    print("All good")
    F= r'C:\Users\Documents\bin%.2f.txt'%t 
    print(t)  
    F= np.loadtxt(F,skiprows=0)
    LogMass = F[:,0]
    LogRed =  F[:,1] 
    value = np.median(LogMass)  
    filesave(*find_nearest(LogMass,LogRed))
    t -=0.2
 else:
    t -=0.2 
    print("empty file")  

输出如下

All good
15.2
All good
15.0
All good
14.8
All good
14.600000000000001
All good
14.400000000000002
All good
14.200000000000003
All good
14.000000000000004
All good
13.800000000000004
All good
13.600000000000005
All good
13.400000000000006
empty file
All good
13.000000000000007
Traceback (most recent call last):
  File "C:\Users\Documents\Codes\Calculate Bin Median.py", line 35, in <module>
    LogMass = F[:,0]
IndexError: too many indices

第二个问题是t 以某种方式从小数点后一位变为 15 位,而最后一位似乎在增加什么? 感谢您的任何帮助

编辑 错误IndexError: too many indices 似乎只适用于只有一行示例的文件...

12.9982324  0.004321374

如果我添加第二行,我不再收到错误,有人可以解释这是为什么吗?谢谢

编辑

我尝试了一个小实验,如果数组只有一行,numpy 似乎不喜欢提取一列。

In [8]: x = np.array([1,3])

In [9]: y=x[:,0]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-9-50e27cf81d21> in <module>()
----> 1 y=x[:,0]

IndexError: too many indices

In [10]: y=x[:,0].shape
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-10-e8108cf30e9a> in <module>()
----> 1 y=x[:,0].shape

IndexError: too many indices

In [11]: 

【问题讨论】:

  • 您看到的小数位是因为它是slowly accumulating a slight error from arithmetic operations(尤其是减法运算14.8-0.2)。如果这是一个问题,您可以选择限制小数位数的显示。
  • 看看返回的numpy数组的形状
  • x.shape。在您的输入 10 中,异常发生在 形状调用之前。

标签: if-statement python-3.x while-loop


【解决方案1】:

您应该使用 try/except 块。比如:

t = 15.2
while t >= 11.4:
    F= r'C:\Users\Documents\bin%.2f.txt'%t 
    try:  
        F = np.loadtxt(F,skiprows=0)
        LogMass = F[:,0]
        LogRed =  F[:,1] 
        value = np.median(LogMass)  
        filesave(*find_nearest(LogMass,LogRed))
    except IndexError:
        print("bad file: {}".format(F))
    else:
        print("file worked!")
    finally:
        t -=0.2

有关异常处理的更多详细信息,请参阅the official tutorial

最后一位数字的问题是由于浮点数的工作方式它们不能代表 base10 数字准确。这可能会带来一些有趣的事情,例如:

In [13]: .3 * 3 - .9
Out[13]: -1.1102230246251565e-16

【讨论】:

  • 抛出错误的文件是一个零字节的空文件。
  • 然后也捕获该异常。
  • 你的意思是跳过第一个文件还是跳过第一行当你说“然后跳过第一个”
  • 我错过了阅读您的代码,并认为您在明确跳过标题时正在跳过标题。
  • 是的,没有标题跳过
【解决方案2】:

要处理单行文件的情况,请将ndmin 参数添加到np.loadtxt(查看其文档):

np.loadtxt('test.npy',ndmin=2)
# array([[ 1.,  2.]])

【讨论】:

    【解决方案3】:

    在名为 ajcr 的用户的帮助下,发现问题是应该在 numpy.loadtxt() 中使用 ndim=2 以确保数组始终为 2 具有维度。

    【讨论】:

      【解决方案4】:

      Python 使用 缩进 来定义 if whilefor 块。

      您的if else 语句看起来不像while 完全缩进。

      我通常使用完整的“tab”键盘键来缩进,而不是“空格

      【讨论】:

      • 强烈建议不要使用标签。至少在科学 python 社区中,4 个空格是标准。您应该使用将翻译 -> 4 个空格的编辑器。并且 OP 代码 仅以混合级别缩进。这可能是由于混合了空格和制表符;)
      猜你喜欢
      • 1970-01-01
      • 2018-12-03
      • 2016-07-23
      • 2020-12-08
      • 1970-01-01
      • 2015-05-05
      • 1970-01-01
      • 2017-02-17
      • 2015-11-08
      相关资源
      最近更新 更多