int()不适用于浮点数?

时间:2016-09-23 01:50:00

标签: python python-3.x floating-point int

我最近在Python 3.5中遇到过这个问题:

>>> flt = '3.14'
>>> integer = '5'
>>> float(integer)
5.0
>>> float(flt)
3.14
>>> int(integer)
5
>>> int(flt)
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    int(flt)
ValueError: invalid literal for int() with base 10: '3.14'

这是为什么?好像它应该返回3。我做错了什么,或者这是否有充分理由发生?

3 个答案:

答案 0 :(得分:5)

BlockingQueue期望包含整数文字的数字或字符串。根据{{​​3}}文档:

  

如果 x 不是数字或 base ,则 x 必须是字符串,{{1} }或Map<String,BlockingQueue<Object>> map = new ConcurrentHashMap<String,BlockingQueue<Object>>(){ @Override public BlockingQueue<Object> put(String key, BlockingQueue<Object> value) { BlockingQueue<Object> current = this.get(key); synchronized (current) { if(current.size() == 10){ current.remove(); } current.add(value.peek()); } return super.put(key, current); } @Override public BlockingQueue<Object> get(Object key) { if(this.contains(key)) return super.get(key); else return new LinkedBlockingQueue<Object>(10); } }; } 实例表示基数中的整数文字。 (强调补充)

含义int()只能转换包含整数的字符串。您可以轻松地执行此操作:

bytes

这会将bytearray转换为浮点数,然后浮点数对int()有效,因为它是一个数字。然后它将通过删除小数部分转换为整数。

答案 1 :(得分:3)

它不起作用,因为flt不是整数的字符串表示形式。您需要先将其转换为float然后转换为int

e.g。

flt = '3.14'
f = int(float(flt))

输出

3

答案 2 :(得分:0)

其他答案已经为您提供了有关您的问题的良好解释,另一种方式可以帮助您理解将要执行的操作:

import sys

for c in ['3.14', '5']:
    try:
        sys.stdout.write(
            "Casting {0} {1} to float({0})...".format(c, c.__class__))
        value = float(c)
        sys.stdout.write("OK -> {0}\n".format(value))
        print('-' * 80)
    except:
        sys.stdout.write("FAIL\n")

    try:
        sys.stdout.write(
            "Casting {0} {1} to int({0})...".format(c, c.__class__))
        value = int(c)
        sys.stdout.write("OK -> {0}\n".format(value))
    except:
        sys.stdout.write("FAIL\n")
        sys.stdout.write("Casting again using int(float({0}))...".format(value))
        value = int(float(c))
        sys.stdout.write("OK -> {0}\n".format(value))
        print('-' * 80)

哪个输出:

Casting 3.14 <class 'str'> to float(3.14)...OK -> 3.14
--------------------------------------------------------------------------------
Casting 3.14 <class 'str'> to int(3.14)...FAIL
Casting again using int(float(3.14))...OK -> 3
--------------------------------------------------------------------------------
Casting 5 <class 'str'> to float(5)...OK -> 5.0
--------------------------------------------------------------------------------
Casting 5 <class 'str'> to int(5)...OK -> 5
相关问题