【问题标题】:Python3 Json Dictionary output price print max with 2 decimal placePython3 Json Dictionary 输出价格打印最大值,小数点后 2 位
【发布时间】:2021-12-15 19:15:44
【问题描述】:

我从 json 字典中管理了最终输出(商品的价格)

从输出价格表中,我想找到最大数量不大于 1.90 的小数点后 2 位

在列表中我们有 45.86834862385321 但我的最终输出必须打印为 1.24

resp2json = rr.json()
a = (resp2json['data']['pencil'])

for b in a:
    final_data = b ['blue'] ['rate']
    print (final_data)

输出

1.2157339821573399
1.2413108242303872
1.2157339821573399
45.86834862385321
1.2165314401622718

【问题讨论】:

    标签: python json python-3.x


    【解决方案1】:

    我认为这段代码将返回小数点后 2 位的输出。

    resp2json = rr.json()
    a = (resp2json['data']['pencil'])
    
    for b in a:
        final_data = b ['blue'] ['rate']
        print (f'{final_data:.2f}')
    

    【讨论】:

      【解决方案2】:

      试试这个:

      data=[
      1.2157339821573399,
      1.2413108242303872,
      1.2157339821573399,
      45.86834862385321,
      1.2165314401622718,
      ]
      temp = 0 
      for row in data:
          if temp < row < 1.9:
              temp = row
      print(round(float(temp),2))
      

      在你的情况下,代码应该是这样的:

      resp2json = rr.json()
      data = (resp2json['data']['pencil'])
      temp = 0
      for row in data:
          if temp < float(row['blue']['rate']) < 1.9:
              temp = float(row['blue']['rate'])
      print(temp)
      

      temp

      【讨论】:

      • 没有回合答案很好,但是当我使用 print(round(temp,2)) TypeError: type str doesn't define round method
      • 可能你的数据是str,你可以像这样添加floatprint(round(float(temp),2))@user12209531 我也更新了答案
      • 谢谢,它按我的意愿工作
      • 其工作不正常`1.2150668286755772 1.2135922330097086 1.2157339821573399 1.2534818941504178 1.2176063303659743 1.2172854534388313 1.2166504381694254 1.217720932924359 1.2157339821573399 1.2150668286755772`输出被打印成1.22不1.25 1.25是最大数量跨度>
      • 1.2150668286755772 1.2135922330097086 1.2157339821573399 1.2534818941504178 1.2176063303659743 1.2172854534388313 1.2166504381694254 1.217720932924359 1.2157339821573399 1.2150668286755772这不是一个有效的数据,你应该用 分割它们,并将它放在一个数组中,或者如果这是你的数据,那么你需要更改代码for row in data.split(" "):
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-15
      • 1970-01-01
      • 2020-10-31
      • 1970-01-01
      相关资源
      最近更新 更多