Home > other >  test numbers and return only the decimal that have one digits on the right side
test numbers and return only the decimal that have one digits on the right side

Time:11-12

I have a list of decimals, I want to filter it using python, and get only decimals with one digit on the right like 2.1 and 1.8, not 2.15:

my_list = [2.1, 2.15, 1.8, 1.995, 1.31, 2.2]

needed output:

[2.1, 1.8, 2.2]

CodePudding user response:

You can use round method in both numpy and pure Python:

numpy:

import numpy as np
my_list = [2.1, 2.15, 1.8, 1.995, 1.31, 2.2]
x = np.array(my_list)
y = x[np.around(x, 1) == x]
>>> y
array([2.1, 1.8, 2.2])
>>> y.tolist()
[2.1, 1.8, 2.2]

Python:

my_list = [2.1, 2.15, 1.8, 1.995, 1.31, 2.2]
>>> [n for n in my_list if round(n, 1) == n]
[2.1, 1.8, 2.2]

Note that it doesn't work in general for numbers that differs by small amounts like epsilon = np.finfo(float).eps. For example 2.2 - epsilon is returned to be decimal in both numpy and Python.

CodePudding user response:

Multiply each element by 100 and check if the last digit is zero:

(my_number * 100) % 10 == 0

CodePudding user response:

condition = lambda x: (num*10)%1==0 and (nums%1)!=1 # Has only 1 trailing digit
res = [num for num in my_list if condition(x)]

Explanation

This program writes a condition that returns true if a number is:

  • Not an integer
  • Is an integer if shifted over by one

This means that it returns True if it has only 1 decimal place, no more, no less.

The second part simply just gets all the numbers in that list that meet that condition, i.e. having 1 decimal place.

  • Related