Python 2.7.5 error printing list of float numbers

2019-07-11 19:25发布

I was trying to answer a question from here (Substracion of two items from two lists). The original problem has two different lists with float values and the goal is to zip them and substract

This code works fine:

Enter=[7.12, 7.14, 7.24, 7.45, 7.28, 7.31, 7.18, 7.25, 7.33, 7.38]
Leave=[7.56, 7.24, 7.48, 7.52, 7.45, 7.57, 7.22, 7.31, 7.37, 7.41]
intervals = map(lambda x, y: y-x, Enter, Leave)

Then:

print intervals

Output:

[0.4399999999999995, 0.10000000000000053, 0.24000000000000021, 0.069999999999999396, 0.16999999999999993, 0.26000000000000068, 0.040000000000000036, 0.059999999999999609, 0.040000000000000036, 0.030000000000000249]

Which seemed really weird for me. And tried this:

print intervals[0]

Output:

0.44

And, last:

for i in intervals:
    print i

Output:

0.44
0.1
0.24
0.07
0.17
0.26
0.04
0.06
0.04
0.03

So the question is. Why is printing floating values one by one print the correct value, while printing entire list doesnt?

Just as a note, I'm using Live Sympy for testing it (Live Sympy, don't have python installed here) which runs Python 2.7.5

1条回答
beautiful°
2楼-- · 2019-07-11 20:24

The print method formats the float however when you print the list it doesn't format its internal values and prints as it is.

    >>> print(intervals[0])   <== formatting is done by print here
    0.44
    >>> intervals[0]
    0.4399999999999995

    >>> print (type(intervals))
    <type 'list'>
    >>> print (type(intervals[0]))
    <type 'float'>
查看更多
登录 后发表回答