我不知道是否有这样的事情 - 但我正在尝试做一个有序的 dict 理解。但是它似乎不起作用?
import requests
from bs4 import BeautifulSoup
from collections import OrderedDict
soup = BeautifulSoup(html, 'html.parser')
tables = soup.find_all('table')
t_data = OrderedDict()
rows = tables[1].find_all('tr')
t_data = {row.th.text: row.td.text for row in rows if row.td }
现在它仍然是一个正常的 dict 理解(我也省略了对汤样板的通常请求)。 有什么想法吗?
最佳答案
您不能直接使用 OrderedDict
进行推导。但是,您可以在 OrderedDict
的构造函数中使用生成器。
试穿一下尺寸:
import requests
from bs4 import BeautifulSoup
from collections import OrderedDict
soup = BeautifulSoup(html, 'html.parser')
tables = soup.find_all('table')
rows = tables[1].find_all('tr')
t_data = OrderedDict((row.th.text, row.td.text) for row in rows if row.td)
关于python - 有 OrderedDict 理解吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32895660/