문제

I have this simple code:

[n/2 for n in range(100, 200)]

But, strangely enough, it returns [50,50,51,51,52,52,etc], so it uses integer division instead of normal one (I need it to output [50,50.5,51,51.5,etc]) Why is it happening?

도움이 되었습니까?

해결책

In Python 2, dividing 2 integers will always produce an integer. (In Python 3, you get "real" division)

You can rewrite your code as:

[n/2.0 for n in range(100, 200)]

or in the case where you have 2 variables:

[float(n)/othervar for n in range(100, 200)]

to get the expected behavior,

or add

from __future__ import division

at the start of the file to get the Python 3 behavior now.

To answer the "why" part of the question, this is a holdover from C's division semantics (although Python made the choice to always floor the result instead of rounding toward 0, so you don't even get the true C integer division semantics.)

다른 팁

Try [n/2.0 for n in range(100, 200)] to make it a float operation. By passing 2 as an integer and all numbers in the range as an integer Python is treating the result as an integer. You need Floating Point Arithmetic. See here for more details.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top