问题
I am having trouble with some variable types in my code. The error that I get now is:
TypeError: can't convert type 'str' to numerator/denominator
The code line in question is the following:
valor_anual[data[0]['Dados'][json_date][0]['geodsg']][year_code] = statistics.mean(valor_mensal_aux)
Here is a snippet of my code to give you guys context:
valor_anual = [0][0]
for city_code in city_codes:
for year_code in year_codes:
valor_mensal_aux = []
for month_code in month_codes:
url_imob = Request(
"https://www.ine.pt/ine/json_indicador/pindica.jsp?op=2&varcd=0010042&Dim1=S3A" + year_code + \
month_code + "&Dim2=" + city_code + "&Dim3=T&lang=PT", headers={'User-Agent': 'XYZ/3.0'})
json_date = year_code + month_code
response = urlopen(url_imob)
data = json.loads(response.read())
valor_mensal_aux.append(data[0]['Dados'][json_date][0]['valor'])
valor_anual[data[0]['Dados'][json_date][0]['geodsg']][year_code] = statistics.mean(valor_mensal_aux)
python_imob = Imob(year_code, valor_anual[city_code][year_code], data['DataUltimoAtualizacao'],
data['Dados'][json_date]['geodsg'])
session.add(python_imob)
session.commit()
session.close()
imobs = session.query(Imob).all()
The JSON that I'm getting data from has the following structure:
[ {
"IndicadorCod" : "0010042",
"IndicadorDsg" : "Valor mediano de avaliação bancária (€/ m²) por Localização geográfica (Município - 2013) e Tipo de construção; Mensal - INE, Inquérito à avaliação bancária na habitação",
"MetaInfUrl" : "https://www.ine.pt/bddXplorer/htdocs/minfo.jsp?var_cd=0010042&lingua=PT",
"DataExtracao" : "2020-06-29T15:55:51.640+01:00",
"DataUltimoAtualizacao" : "2020-06-29",
"UltimoPref" : "Maio de 2020",
"Dados" : {
"202005" : [ {
"geocod" : "1701106",
"geodsg" : "Lisboa",
"dim_3" : "T",
"dim_3_t" : "Total",
"valor" : "3084"
} ]
}
} ]
回答1:
How about typecasting
valor_anual[int(data[0]['Dados'][json_date][0]['geodsg'])][int(year_code)]
回答2:
It is impossible to give an exact solution without the full source code, however I suspect your issue is that you are attempting to take the mean of valor_mensal_aux which contains string elements. Try converting "valor" to an integer before appending it to the list:
valor_mensal_aux.append(int(data[0]['Dados'][json_date][0]['valor']))
来源:https://stackoverflow.com/questions/63847926/typeerror-cant-convert-type-str-to-numerator-denominator