Receiving 0.0 when expecting a non-zero value after division
Hai... i am facing a problem while inserting valu开发者_Go百科es to an array. the programming language using is python. the problem is, i need to insert a value to array after performing a division. but every the value in array is always 0.0 . i am attaching the code here....
print len(extract_list1)
ratio1=range(len(extract_list1))
i=0
for word in extract_list1:
ratio1[i]=float(i/len(extract_list1))
print extract_list1[i],ratio1[i]
i+=1
ratio2=range(len(extract_list2))
i=0
for word in extract_list2:
ratio2[i]=float(i/len(extract_list2))
print extract_list2[i],ratio2[i]
i+=1
My best guess is that you are performing integer division and then converting to a float yielding the value of 0.0
which is what gets stuck in the list. you want to convert to float before the division. Sift through that wall of code and find out
- where you are inserting the value into the list.
- Where that value is generated.
then post the code that generates the value. If the value is making it into the list (and you seem to indicate that it is), then this has nothing to do with lists and everything to do with how you are generating the value.
As Roger Pate points out in the comments, you can place the line from __future__ import division
as the very first line of your source code (or the first line after the encoding if you are using one) and it will automatically convert all division to floating point division. you can then use //
as an operator for when you explicitly want truncating integer division.
looking at your code, the problem is
float(i/len(extract_list2))
this should be
float(i)/len(extract_list2))
also, because you are taking the lengths of extract_list2
and extract_list1
multiple times, it would be better to create variables to store them.
L1 = len(extract_list1)
L2 = len(extract_list2)
you can then reference the variables as long as you are not changing the lengths of the lists. This will save you some function calls and make your code more concise and readable.
精彩评论