简体   繁体   English

如何使代码同时接受 int 和 float 类型的值作为 double 类型? - Python

[英]How to make the code accept both int and float type values as double type? - Python

I have dataset which have mixed values, in which few values are float(eg 3.4) and few are int (eg 3.0).我有具有混合值的数据集,其中很少有值是浮点数(例如 3.4),很少是整数(例如 3.0)。 I want to check if all the values are double.我想检查所有值是否都是双倍的。 I want that if the values are either int or float, they are accepted as double datatype.我希望如果值是 int 或 float,它们被接受为 double 数据类型。

I tried doing:我试着做:


data = [3.0, 3.4, 3.2, 3.0, 3.1]

for valuedata in data:
  is_double = isinstance(valuedata, float)
  print(is_double)

The result is coming out to be FALSE, where as i want that int and float both should be accepted as double.结果是 FALSE,因为我希望 int 和 float 都应该被接受为 double。

Thanks谢谢

You can see if it's an instance of numbers.Number.你可以看看它是否是numbers.Number的一个实例。

>>> import numbers
>>> isinstance(1.1, numbers.Number)
True
>>> isinstance(1, numbers.Number)  
True
>>> 

You can check for multiple allowed types by passing a tuple to isinstance() :您可以通过将元组传递给isinstance()来检查多个允许的类型:

is_double = isinstance(valuedata, (int, float))

Also note that Python's int has unlimited precision, which could be too large to fit into a C/C++ double .另请注意,Python 的int具有无限精度,它可能太大而无法放入 C/C++ double中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM