【问题标题】:TypeError: 'float' object is not subscriptable when calc temp averages from jsonTypeError:当从 json 计算温度平均值时,'float' 对象不可下标
【发布时间】:2021-02-13 08:37:30
【问题描述】:

我试图弄清楚如何从 json 文件中平均温度,但在转换时遇到了问题。它不断抛出错误:TypeError: 'float' object is not subscriptable when calc temp averages from json

>>> import urllib.request
>>> import json
>>>
>>> zipcode_list = ["72714","71640","72454","71834","72223","72110"]
>>> for one_zipcode in zipcode_list:
...     link = "https://api.openweathermap.org/data/2.5/weather?zip="+one_zipcode+"&appid=e7c3fb6e681c8f7bb59af33f1dc8bbca"
...     f = urllib.request.urlopen(link)
...     data = f.read()
...     weather = json.loads(data)
...     n = (weather["name"])
...     x = (weather["main"]["temp"])
...     fh = (x-273.1)*9/5+32
...     total = round(fh, 2)
...     print (n, ":", total, "Farenheit")
...     avg = (x["main"]["temp"].mean())
...     print(avg)
...
Bella Vista : 11.93 Farenheit
Traceback (most recent call last):
  File "<stdin>", line 11, in <module>
TypeError: 'float' object is not subscriptable

【问题讨论】:

  • 请重新格式化您的代码。
  • 您遇到的具体问题是什么?
  • 当我尝试计算平均值时,它会抛出 TypeError: 'float' object is not subscriptable 的错误
  • 请使用完整的错误回溯更新您的问题。
  • 我想我昨天帮助了你的同学。 stackoverflow.com/questions/66180055/…

标签: python json api average


【解决方案1】:

您的意思是收集total 的所有值并求均值吗?

import statistics

temps=[]
for one_zipcode in zipcode_list:
    link = link = "https://api.openweathermap.org/data/2.5/weather?zip="+one_zipcode+"&appid=e7c3fb6e681c8f7bb59af33f1dc8bbca"
    f = urllib.request.urlopen(link)
    data = f.read()
    weather = json.loads(data)
    n = weather["name"]
    x = weather["main"]["temp"]
    fh = (x - 273.1) * 9 / 5 + 32
    total = round(fh, 2)
    print(n, ":", total, "Farenheit")
    temps.append(total)
avg = statistics.mean(temps)
print(avg)

【讨论】:

  • 哦,哇,非常感谢。我想多了这个问题。甚至没有意识到追加。非常感谢!!!!!!
【解决方案2】:

您将浮点数分配给x,然后您尝试下标x,这就是您看到错误消息的原因。见下文。

x = (weather["main"]["temp"])
...
avg = (x["main"]["temp"].mean())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 2020-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多