• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • YouClaw
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
三___毛
博客园    首页    新随笔    联系   管理    订阅  订阅

python for dict append到list 总会覆盖list中所有的元素



 b = ['/Portal/Index/detial/id/78122/type/357', '/Portal/Index/detial/id/78121/type/357', '/Portal/Index/detial/id/78120/type/357', '/Portal/Index/detial/id/78119/type/357', '/Portal/Index/detial/id/78118/type/357', '/Portal/Index/detial/id/78117/type/357', '/Portal/Index/detial/id/78116/type/357', '/Portal/Index/detial/id/78115/type/357'] itemss = EggpriceItem() ab = [] for i in range(0,len(b)): itemss['_url'] = b[i] ab.append(itemss) # print(itemss) print(ab)
结果:[{'_url': '/Portal/Index/detial/id/78115/type/357'}, {'_url': '/Portal/Index/detial/id/78115/type/357'}, {'_url': '/Portal/Index/detial/id/78115/type/357'}, {'_url': '/Portal/Index/detial/id/78115/type/357'}, {'_url': '/Portal/Index/detial/id/78115/type/357'}, {'_url': '/Portal/Index/detial/id/78115/type/357'}, {'_url': '/Portal/Index/detial/id/78115/type/357'}, {'_url': '/Portal/Index/detial/id/78115/type/357'}]

今天写爬虫时,处理list时遇到的一个问题

debug时,发现每次执行append后 ab list里的元素都会被刷掉,debug了无数遍,不得其解,突然灵机一动,想到了百度,百度一番果然找到了问题所在,大体是变量指向的内存相关,虽然我没明白具体原因。不影响问题的解决,后续我再补充具体原因

b = ['/Portal/Index/detial/id/78122/type/357', '/Portal/Index/detial/id/78121/type/357', '/Portal/Index/detial/id/78120/type/357', '/Portal/Index/detial/id/78119/type/357', '/Portal/Index/detial/id/78118/type/357', '/Portal/Index/detial/id/78117/type/357', '/Portal/Index/detial/id/78116/type/357', '/Portal/Index/detial/id/78115/type/357']
    
    ab = []
    for i in range(0,len(b)):
        itemss = EggpriceItem()
        itemss['_url'] = b[i]
        ab.append(itemss)
        # print(itemss)
    print(ab)
结果:[{'_url': '/Portal/Index/detial/id/78122/type/357'}, {'_url': '/Portal/Index/detial/id/78121/type/357'}, {'_url': '/Portal/Index/detial/id/78120/type/357'}, {'_url': '/Portal/Index/detial/id/78119/type/357'}, {'_url': '/Portal/Index/detial/id/78118/type/357'}, {'_url': '/Portal/Index/detial/id/78117/type/357'}, {'_url': '/Portal/Index/detial/id/78116/type/357'}, {'_url': '/Portal/Index/detial/id/78115/type/357'}]

dict 放在for循环下面,就能正确得到我想要的结果了。

为了避免后面再犯错,故记录下来

posted @ 2020-03-21 22:11  三___毛  阅读(736)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3