I am searching for the most pythonic way to check, whether one or more elements in a list are even multiples of a predefined number with a predefined tolerance. An example is given below:
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]
Any suggestions are very appreciated.
How about
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)]
The first part determines if the division is within the tolerance of an integer and the second part figures out if this integer is divisible by 2.
How about
print print([int(abs(x - round(x / myNumber) * myNumber) <= myTolerance and round(x / myNumber) > 1.5) for x in myList])
Output:
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.