从浮动输出中智能地删除“.0”

Inteligently remove ".0" from float output

我的函数有这样的结果片段:

{
    "id": "7418", 
    "name": "7.5"
}, 
{
    "id": "7419", 
    "name": "8.0"
}, 
{
    "id": "7420", 
    "name": "8.5"
}, 
{
    "id": "7429", 
    "name": "9.0"
}, 

我做的很简单:

[{'id': opt['size'], 'name': '{}'.format(float(opt['value']))} for opt in options]

我不想对 ".0" 进行任何替换,我对如何将数据正确转换为感兴趣:

{
    "id": "7429", 
    "name": "9"
}

好吧,如果这是一个字典列表:

[{'id': i['id'], 'name': ['{:.1f}', '{:.0f}'][float(i['name']).is_integer()].format(float(i['name']))} for i in your_list]

由于name的type值是String,所以我们也可以使用split方法

演示

input_list = [{'id': '7418', 'name': '7.5'}, {'id': '7419', 'name': '8.0'}, {'id': '7420', 'name': '8.5'}, {'id': '7429', 'name': '9.0'}]

result = []

for i in input_list:
    # Split by .
    tmp = i["name"].split(".")
    try:
        #- Type casting.
        tmp1 = int(tmp[1])
    except IndexError:
        result.apend({"id":i["id"], "name":i["name"]})
        continue
    except ValueError:
        print "Value exception, Check input:-", i
        continue

    #- Check after decimal number is equal to 0 or not.
    if tmp1==0:
        val = tmp[0]
    else:
        val = i["name"]
    result.append({"id":i["id"], "name":val})


print "Result:-", result

输出:

Result:- [{'id': '7418', 'name': '7.5'}, {'id': '7419', 'name': '8'}, {'id': '7420', 'name': '8.5'}, {'id': '7429', 'name': '9'}]

如果您只想将 表示整数的 float 个对象 转换为 int(即将 9.0 转换为 9但保持 9.5 不变),您可以使用 float.is_integer 检查:

>>> numbers = [1.0, 1.2, 1.4, 1.6, 1.8, 2.0]
>>> numbers = map(lambda f: int(f) if f.is_integer() else f, numbers)
>>> numbers
[1, 1.2, 1.4, 1.6, 1.8, 2]
>>> map(type, numbers)
[<type 'int'>, <type 'float'>, <type 'float'>, <type 'float'>, <type 'float'>, <type 'int'>]

或者,如果您想将转换应用于字符串(即不将 JSON 转换为 Python 对象),您可以使用正则表达式 (see demo):

>>> import re
>>> data = """
             {
                 "id": "7418", 
                 "name": "7.5"
             }, 
             {
                 "id": "7419", 
                 "name": "8.0"
             }, """
>>> print re.sub(r'"(\d+)\.0"', r'""', data)

             {
                 "id": "7418", 
                 "name": "7.5"
             }, 
             {
                 "id": "7419", 
                 "name": "8"
             }, 

再次注意,"7.5" 没有改变,但是 "8.0" 被替换为 "8"

使用 .15g

格式化您的号码
>>> format(555.123, '.15g')
555.123
>>> format(5.0, '.15g')
5

尽管它将对接近零的数字使用科学指数格式:

>>> format(0.00001, '.16g')
1e-05

对于小数点前有 16 位以上数字的数字。

请注意,您不需要使用 '{}'.format()format 上面的内置函数在这里效果更好。