我正在制作一个函数,该函数将制作一个列表,其中包括请求列表的直方图和请求值用作直方图的值。高于请求值的值最后包含。
程序正在处理一个按数字升序排序的列表,但是当使用一个未排序的列表作为输入时,程序似乎丢弃了随机值,并且不以相同的方式计算。代码:
def histogram(sample, binBoundaries):
c=0
if not binBoundaries:
li = [len(sample)]
return print(li)
for x in sample:
if x > binBoundaries[-1]: #if the value is greater than last bin
c = c+1 #number of values greater increases
for eachbin in binBoundaries: #for each bin
dic[eachbin] = 0 #initial value = 0 to account for no number
for x in sample: #for each value wanted to calculate for
if x <= eachbin: #if the number falls into the bin
dic[eachbin] += 1 #the number of values in the bin increases
sample.remove(x)
for i in dic:
listofvalues.append(dic[i])
listofvalues.append(c)
print(listofvalues)
直方图([5,4,2,3],[3])
将导致输出为[1,2],而实际输出应为[2,2]
是不是有什么我没有看到的东西使得这个数字没有被计算出来?如果可以的话,让我知道我哪里做错了!
你的问题是你正在从列表sample
中删除项目,而你正在迭代它,这是一个坏主意,因为它会导致跳过一些元素。
试着取出行sample.remove(x)
,你应该得到预期的结果。如果确实需要从输入列表中删除元素,则应该进行重构,以确保仍然检查列表中的每个元素。一种选择是使用for x in reversed(sample)
对列表进行反向迭代。
它看起来也像你可能在错误的地方删除元素,sample.remove(x)
看起来应该在if
直接在它上面。试试下面的代码:
...
for eachbin in binBoundaries: #for each bin
dic[eachbin] = 0 #initial value = 0 to account for no number
for x in reversed(sample): #for each value wanted to calculate for
if x <= eachbin: #if the number falls into the bin
dic[eachbin] += 1 #the number of values in the bin increases
sample.remove(x)
...