Python 是否有一个有序的理解?

Python 是否有一个有序的理解?,python,beautifulsoup,Python,Beautifulsoup,我不知道是否有这样的事情,但我正在尝试做一个有序的听写理解。但它似乎不起作用 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'

我不知道是否有这样的事情,但我正在尝试做一个有序的听写理解。但它似乎不起作用

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 }
现在,这只是一个普通的听写理解(我也省略了对汤样板的通常要求)。
有什么想法吗?

你不能直接用
OrderedDict
进行理解。但是,您可以在构造函数中为
orderedict
使用生成器

试试这个尺码:

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)

不,没有所谓有条理的字典,你只需要一本普通的字典。事实上,您之前已将OrderedICT分配给该名称并不重要。没有创建空的dict,然后使用带有OrderedICT或任何dict的dict comp向其添加元素的情况。一旦您重新绑定名称
t\u data
,它将不再指向您的OrderedICT。很高兴我能提供帮助!事实上,我自己最近才发现这一点。