我面临以下问题,对于数据“结果”中的pa,显示以下错误:"TypeError:列表索引必须是整数或切片,而不是字符串“。你能建议我应该对代码进行哪种操作才能让它运行而不显示错误?
with open("data/indicePA/indicePA.tsv", 'w') as f_indice_pa , open("data/indicePA/otherPA.tsv", 'w') as f_other:
writer_indice_pa = csv.writer(f_indice_pa, delimiter ='\t')
writer_other_pa = csv.writer(f_other, delimiter ='\t')
count = 0
res = ["cf", "cod_amm", "regione", "provincia", "comune", "indirizzo", "tipologia_istat", "tipologia_amm"]
writer_indice_pa.writerow(res)
writer_other_pa.writerow(["cf"])
for pa in data["result"]:
esito = pa["esitoUltimoTentativoAccessoUrl"]
if esito == "successo":
cf = pa["codiceFiscale"]
if cf in cf_set_amm:
try:
cod_amm = df_amm.loc[df_amm['Cf'] == cf].iloc[0]['cod_amm']
take0 = df_amm.loc[df_amm['cod_amm'] == cod_amm].iloc[0]
regione = take0['Regione'].replace("\t", "")
provincia = str(take0['Provincia']).replace("\t", "")
comune = take0['Comune'].replace("\t", "")
indirizzo = take0['Indirizzo'].replace("\t", "")
tipologia_istat = take0['tipologia_istat'].replace("\t", "")
tipologia_amm = take0['tipologia_amm'].replace("\t", "")
res = [cf, cod_amm, regione, provincia, comune, indirizzo, tipologia_istat, tipologia_amm]
writer_indice_pa.writerow(res)
except: # catch *all* exceptions
print("CF in df_amm",cf)
elif cf in cf_set_serv_fatt:
try:
cod_amm = df_serv_fatt.loc[df_serv_fatt['Cf'] == cf].iloc[0]['cod_amm']
take0 = df_amm.loc[df_amm['cod_amm'] == cod_amm].iloc[0]
regione = take0['Regione'].replace("\t", "")
provincia = str(take0['Provincia']).replace("\t", "")
comune = take0['Comune'].replace("\t", "")
indirizzo = take0['Indirizzo'].replace("\t", "")
tipologia_istat = take0['tipologia_istat'].replace("\t", "")
tipologia_amm = take0["tipologia_amm"].replace("\t", "")
res = [cf, cod_amm, regione, provincia, comune, indirizzo, tipologia_istat, tipologia_amm]
writer_indice_pa.writerow(res)
except: # catch *all* exceptions
#e = sys.exc_info()[0]
print("CF in df_serv_fatt",cf)
else:
#print(cf, " is not present")
count = count + 1
writer_other_pa.writerow([cf])
#if(count % 100 == 0):
#print(cf)
print("Totale cf non presenti in IndicePA: ", count)
f_indice_pa.flush()
f_other.flush()
I expect to obtain the following statement "Totale cf non presenti in IndicePA: 1148", because this code has been already run. But I face this problem. How to overcome it? Is there any manipulation that I can make to this original code?提前感谢您的帮助。可以在以下链接中找到代码的更广泛的解释:link resource
发布于 2019-02-13 02:50:32
根据用于解析该json文件的json模块的文档。

该图表可在https://docs.python.org/2/library/json.html的18.2.2节中找到
看起来你的json对象正在被解析成一个列表。根据该图表,对象必须是数组。像这样..。
[
{
"result" : { someObject }
}
]一个简单的修复方法可能是编辑json,以便将其正确解析为字典。例如..。
{
"result": {
someObjectStuff
}
}另一个修复方法可能是访问列表中的第一个元素。如果您的json如下所示
[
{
"result" : { someObject }
}
]然后将代码更改为
for pa in data[0]["result"]:或许也能解决这个问题。
https://stackoverflow.com/questions/54656377
复制相似问题