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循环下面,就能正确得到我想要的结果了。
为了避免后面再犯错,故记录下来