TypeError: 'int' object is not subscriptable

今天在用Python爬取58同城的租房信息,在遍历循环上发现TypeError: 'int' object is not subscriptable错误,
for item in range(0,len(dlist)):
        print("第("+str(item+1)+")条房产信息")
        print("标题信息:"+item[1].strip())
        print("户型信息:"+item[2].strip().replace(" ","").replace("    "," "))
        print("价格信息:"+item[3].strip()+" 元/月")
        print("图片信息:"+item[0].strip())
        print("==="*20)
        time.sleep(1)
目的是要让item从0开始遍历循环,第一句print可以正常输出,从第二句print开始报错
print("标题信息:"+item[1].strip())
TypeError: 'int' object is not subscriptable

在网上查了遍才在stackoverflow上找到答案,原来在for in range()中,item属于int类型,而非list,所以用列表的写法会报类型错误,原来这个遍历循环我是for item in dlist,所以后面改造没有考虑到item的类型

改成这样就没错啦!

  for item in range(0,len(dlist)):
        print("第("+str(item+1)+")条房产信息")
        print("标题信息:"+dlist[item][1].strip())
        print("户型信息:"+dlist[item][2].strip().replace(" ","").replace("    "," "))
        print("价格信息:"+dlist[item][3].strip()+" 元/月")
        print("图片信息:"+dlist[item][0].strip())
        print("==="*20)
        time.sleep(1)

猜你喜欢

转载自blog.csdn.net/levon2018/article/details/80371593
今日推荐