Python function that identifies if a number is closer to 0 or 1

  • A+
Category:Languages

I have a list of numbers. Below is an example:

[[-2.10044520e-04  1.72314372e-04  1.77235336e-04 -1.06613465e-04 6.76617611e-07  2.71623057e-03 -3.32789944e-05  1.44899758e-05 5.79249863e-05  4.06502549e-04 -1.35823707e-05 -4.13955189e-04 5.29862793e-05 -1.98286005e-04 -2.22829175e-04 -8.88758230e-04 5.62228710e-05  1.36249752e-05 -2.00474996e-05 -2.10090068e-05 1.00007518e+00  1.00007569e+00 -4.44597417e-05 -2.93724453e-04 1.00007513e+00  1.00007496e+00  1.00007532e+00 -1.22357142e-03 3.27903892e-06  1.00007592e+00  1.00007468e+00  1.00007558e+00 2.09869172e-05 -1.97610235e-05  1.00007529e+00  1.00007530e+00 1.00007503e+00 -2.68725642e-05 -3.00372853e-03  1.00007386e+00 1.00007443e+00  1.00007388e+00  5.86993822e-05 -8.69989983e-06 1.00007590e+00  1.00007488e+00  1.00007515e+00  8.81850779e-04 2.03875532e-05  1.00007480e+00  1.00007425e+00  1.00007517e+00 -2.44678912e-05 -4.36556267e-08  1.00007436e+00  1.00007558e+00 1.00007571e+00 -5.42990711e-04  1.45517859e-04  1.00007522e+00 1.00007469e+00  1.00007575e+00 -2.52271817e-05 -7.46339417e-05 1.00007427e+00]] 

I want to know if each of the number is close to 0 or 1. Is there a function in python that could do it or do I have to do it manually?

 


A straightforward way:

lst=[0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9]  closerTo1 = [x >= 0.5 for x in lst] 

Or you can use np:

import numpy as np lst=[0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9]  arr = np.array(lst) closerTo1 = arr >= 0.5 

Note that >= 0.5 can be changed to > 0.5, however you choose to treat it.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: