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]
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
.
将每个元素乘以 100 并检查最后一位数字是否为零:
(my_number * 100) % 10 == 0
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)]
This program writes a condition that returns true if a number is:
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, ie having 1 decimal place.
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.