为什么下面的循环总是返回0的结果?

2024-07-05 14:02:26 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我试着生成一个频谱,为了做到这一点,我试着把我的数据从一个列中分类,我附加了数据,叫做minorallelefreq。由于某些原因,代码不起作用,因为我得到的所有5个箱子的值都是0。你知道吗

代码如下:

minprop = 0
minprop1 = 0
minprop2 = 0
minprop3 = 0
minprop4 = 0 

for x in range(1,100):

    if minorallelefreq[x] <= 0.1:
        minprop = minprop + 1 
    if minorallelefreq[x] > 0.1 and minorallelefreq[x] <= 0.2: 
        minprop1 = minprop1 + 1 
    if minorallelefreq[x] > 0.2 and minorallelefreq[x] <= 0.3: 
        minprop2 = minprop2 + 1
    if minorallelefreq[x] > 0.3 and minorallelefreq[x] <= 0.4: 
        minprop3 = minprop3 + 1
    if minorallelefreq[x] > 0.4 and minorallelefreq[x] <= 0.5:
        minprop4 = minprop4 + 1



bin1 = minprop/float(counter)
bin2 = minprop1/float(counter)
bin3 = minprop2/float(counter)
bin4 = minprop3/float(counter)
bin5 = minprop4/float(counter)  
print "Bin1 (0-0.1)=", bin1, "\t", "Bin2 (0.1-0.2)=", bin2, "\t", "Bin3 (0.2-0.3)=", bin3, "\t", "Bin4 (0.3-0.4)=", bin4, "\t", "Bin5 (0.4-0.5)=", bin5

所以循环不起作用的原因是python没有将我的值(都是小数)读取为小数。所以,我不得不把它改成float(minorallelefreq[x]),它就成功了。


Tags: and数据代码ifcounter原因floatbin2
2条回答
if minorallelefreq[x] <= int(0.1):
    minprop = minprop + 1 
if minorallelefreq[x] > 0.1 and minorallelefreq[x] <= 0.2: 
    minprop1 = minprop1 + 1 

意味着对值>;0和<;=0.1不采取任何操作。如果删除int()调用会发生什么?你知道吗

此外,对于值>;0.4:

if minorallelefreq[x] > 0.4 and minorallelefreq[x] <= 0.4:  # never True
    minprop4 = minprop4 + 1                                 # indentation??

一般来说,您应该研究链式比较:

if 0.1 < minorallelefreq[x] <= 0.2:   # much easier to read, and faster.
    # etc.

这段代码中有几个可能的错误

  1. int(0.1)=>;0,因此minprop将始终为0,除非存在负值
  2. minprop4没有缩进,而且永远不会设置,因为值不能同时为>;0.4和<;=0.4
  3. 假设100个元素,它们都在0到0.4之间

我建议您尝试根据实际值而不是预期值自动bucketize:

import collections
buckets = collections.Counter()

for value in minorallfreq:
    bucket = int(value * 10) / 10.0
    buckets[bucket] += 1

相关问题 更多 >