You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python筛选小数点后仅1位的十进制数值

Python过滤仅保留1位小数的数值实现方案

方法1:字符串判断法(常规场景推荐)

直接将数值转为字符串分割判断小数位长度,代码简单易读:

my_list = [2.1, 2.15, 1.8, 1.995, 1.31, 2.2]
# 过滤逻辑:有小数点且小数部分长度为1的数值
filtered_list = [n for n in my_list if len(str(n).split('.')[-1]) == 1 and '.' in str(n)]
print(filtered_list)

输出结果:[2.1, 1.8, 2.2]

方法2:Decimal精确判断法(高精度场景适用)

避免浮点数底层存储精度问题导致的判断误差:

from decimal import Decimal

my_list = [2.1, 2.15, 1.8, 1.995, 1.31, 2.2]
filtered_list = [n for n in my_list if abs(Decimal(str(n)).as_tuple().exponent) == 1]
print(filtered_list)

内容的提问来源于stack exchange,提问作者Khaled Koubaa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 21:15:10