else语句不会返回循环 [英] else statement does not return to loop

查看:206
本文介绍了else语句不会返回循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a code that opens a file, calculates the median value and writes that value to a separate file. Some of the files maybe empty so I wrote the following loop to check it the file is empty and if so skip it, increment the count and go back to the loop. It does what is expected for the first empty file it finds ,but not the second. The loop is below

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位,最后一个位置似乎在增加什么呢?
感谢您提供的所有帮助

A second issue is that t somehow goes from one decimal place to 15 and the last place seems to incrementing whats with that? Thanks for any and all help

编辑
错误 IndexError:索引太多似乎只适用于只有一行示例的文件...

EDIT The error IndexError: too many indices only seems to apply to files with only one line example...

12.9982324  0.004321374

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

If I add a second line I no longer get the error can someone explain why this is? Thanks

编辑

我尝试了一个小实验,似乎numpy没有比如在数组只有一行时提取一列。

I tried a little experiment and it seems numpy does not like extracting a column if the array only has one row.

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]: 


推荐答案

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

To deal with the one line file case, add the ndmin parameter to np.loadtxt (review its doc):

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

这篇关于else语句不会返回循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆