创建字典列表将产生同一字典的副本列表
- 2025-02-28 08:23:00
- admin 原创
- 74
问题描述:
iframe
我想从网页上获取所有内容。
代码:
site = "http://" + url
f = urllib2.urlopen(site)
web_content = f.read()
soup = BeautifulSoup(web_content)
info = {}
content = []
for iframe in soup.find_all('iframe'):
info['src'] = iframe.get('src')
info['height'] = iframe.get('height')
info['width'] = iframe.get('width')
content.append(info)
print(info)
pprint(content)
结果print(info)
:
{'src': u'abc.com', 'width': u'0', 'height': u'0'}
{'src': u'xyz.com', 'width': u'0', 'height': u'0'}
{'src': u'http://www.detik.com', 'width': u'1000', 'height': u'600'}
结果pprint(content)
:
[{'height': u'600', 'src': u'http://www.detik.com', 'width': u'1000'},
{'height': u'600', 'src': u'http://www.detik.com', 'width': u'1000'},
{'height': u'600', 'src': u'http://www.detik.com', 'width': u'1000'}]
为什么内容的值不对?它应该和我 时的值相同print(info)
。
解决方案 1:
您不是为每个 iframe 创建单独的字典,而是一遍又一遍地修改同一个字典,并在列表中不断添加对该字典的其他引用。
请记住,当您执行类似的操作时content.append(info)
,您并没有复制数据,而只是附加了对数据的引用。
您需要为每个 iframe 创建一个新字典。
for iframe in soup.find_all('iframe'):
info = {}
...
更好的是,你不需要先创建一个空字典。只需一次性创建它即可:
for iframe in soup.find_all('iframe'):
info = {
"src": iframe.get('src'),
"height": iframe.get('height'),
"width": iframe.get('width'),
}
content.append(info)
还有其他方法可以实现这一点,例如遍历属性列表,或者使用列表或字典理解,但很难提高上述代码的清晰度。
解决方案 2:
您误解了 Pythonlist
对象。它类似于 C。pointer-array
它实际上并没有“复制”您附加到它的对象。相反,它只是存储指向该对象的“指针”。
尝试以下代码:
>>> d={}
>>> dlist=[]
>>> for i in xrange(0,3):
d['data']=i
dlist.append(d)
print(d)
{'data': 0}
{'data': 1}
{'data': 2}
>>> print(dlist)
[{'data': 2}, {'data': 2}, {'data': 2}]
那么为什么print(dlist)
不一样呢print(d)
?
下面的代码向你展示了原因:
>>> for i in dlist:
print "the list item point to object:", id(i)
the list item point to object: 47472232
the list item point to object: 47472232
the list item point to object: 47472232
因此你可以看到里面的所有项目dlist
实际上都指向同一个dict
对象。
这个问题的真正答案是通过使用 来附加目标项目的“副本” d.copy()
。
>>> dlist=[]
>>> for i in xrange(0,3):
d['data']=i
dlist.append(d.copy())
print(d)
{'data': 0}
{'data': 1}
{'data': 2}
>>> print dlist
[{'data': 0}, {'data': 1}, {'data': 2}]
尝试一下这个id()
技巧,你会看到列表项实际上指向完全不同的对象。
>>> for i in dlist:
print "the list item points to object:", id(i)
the list item points to object: 33861576
the list item points to object: 47472520
the list item points to object: 47458120
解决方案 3:
如果你想要一行:
list_of_dict = [{} for i in range(list_len)]
解决方案 4:
info
是指向字典的指针——你不断地将同一个指针添加到列表中contact
。
插入info = {}
循环应该可以解决问题:
...
content = []
for iframe in soup.find_all('iframe'):
info = {}
info['src'] = iframe.get('src')
info['height'] = iframe.get('height')
info['width'] = iframe.get('width')
...
相关推荐
热门文章
项目管理软件有哪些?
热门标签
曾咪二维码
扫码咨询,免费领取项目管理大礼包!
云禅道AD