Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 2.7 将列表除以整数并检查列表中的任何元素是否为整数(PYTHON)_Python 2.7_Floating Point_Integer_Division - Fatal编程技术网

Python 2.7 将列表除以整数并检查列表中的任何元素是否为整数(PYTHON)

Python 2.7 将列表除以整数并检查列表中的任何元素是否为整数(PYTHON),python-2.7,floating-point,integer,division,Python 2.7,Floating Point,Integer,Division,嘿,我是python的初学者,我写了这段代码,但它不起作用,我确信这是我看不到的小东西 myList = [10,22,30,40] myInt = 3.0 newList = [x/myInt for x in myList] if any(isinstance(y,int) for y in newList): print newList else: print "None are integers" 因为30/3=1

嘿,我是python的初学者,我写了这段代码,但它不起作用,我确信这是我看不到的小东西

    myList = [10,22,30,40]
    myInt = 3.0
    newList = [x/myInt for x in myList]
    if any(isinstance(y,int) for y in newList):
        print newList
    else:
        print "None are integers"
因为30/3=10,10是整数,所以它应该打印出newList,它是[3.33,7.33,10.0,13.33],但是它的打印“None是整数”


我确信“if any(isinstance(y,int)表示newList中的y)”有问题,但无法确定是什么问题

类型在Python中是一个严格的特性。任何涉及浮点的操作都会产生另一个浮点,即使该值可以精确地表示为整数。这样的东西可能适合你:

myList = [10,22,30,40]
myInt = 3
newList = [x%myInt for x in myList] # A list of remainders now, not quotients
if any(y == 0 for y in newList):
    print [ x/(1.0*myInt) for x in myList ]   # Reproduce your original myList 
else:
    print "None are integers"

以下是您的基本问题:

>>> 30/3
10
>>> 30/3.0
10.0
>>> type(10.0)
<type 'float'>
>30/3
10
>>> 30/3.0
10
>>>类型(10.0)
整数是一个整数,没有小数部分。浮点是一个数字,但带有小数部分(小数点),即使其
.0
与上述情况相同

虽然它们都是数字,但对于Python来说,它们是两种不同的类型


由于您要除以一个浮点数,因此所有结果都将是浮点数。因此,您的检查失败,因为虽然它们是数字,但不是整数。

在2.7+中,您可以检查
浮点值是否可以表示为
整数:

myList = [10,22,30,40]
myInt = 3.0

divided = (el / myInt for el in myList) # generator over floats
is_integer = [el for el in divided if el.is_integer()] # filter ints only
# [10.0]
所以你的支票是:

if any((el / myInt).is_integer() for el in myList):
    # do something

newList
项是浮动。
3.0
也不是整数。