使用Python查找列表中的数字的倍数

时间:2015-08-05 23:18:23

标签: python python-2.7

我正在寻找最灵活的检查方式,列表中的一个或多个元素是否是具有预定义容差的预定义数字的倍数。下面给出一个例子:

myNumber=3.5
myList=[0,0.5,1,1.5,2,2.5,3,3.5,4,4.5,5,5.5,6,6.5,7,7.5,8,8.5,9,9.5]
myTolerance=0.5

myResult=[0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0]

非常感谢任何建议。

2 个答案:

答案 0 :(得分:4)

怎么样

from numpy import mod, floor
withinTolAbove=[int(mod(number, myNumber) <= myTolerance and
                mod(floor(number / myNumber), 2) == 0) for number in myList]
withinTolBelow=[int(mod(number + myTolerance, myNumber) <= myTolerance and
                mod(floor((number + myTolerance) / myNumber), 2) == 0) for number in myList]
myResult=[max(i1, i2) * int(number > myTolerance) for i1, i2, number in zip(withinTolAbove, withinTolBelow, myList)]

第一部分确定除法是否在整数的容差范围内,第二部分判断该整数是否可被2整除。

答案 1 :(得分:0)

怎么样

print print([int(abs(x - round(x / myNumber) * myNumber) <= myTolerance and round(x / myNumber) > 1.5) for x in myList])

输出:

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0]