python 将sql结果转换为树层次结构
我有一个 SQL 查询,它在每行上返回 3 个级别的数据链(即国家、县、城市)。每个国家可能有超过 1 个县,每个县可能有超过 1 个城市。
结果集: “英国” “兰开夏郡” “伯恩利” “英国” “兰开夏郡” “布莱克本” “英国” “默西塞德郡” “利物浦” “英国” “西约克郡” “利兹” “英国”“西约克郡”“约克”
我如何迭代Python中的结果集来创建类似的东西:
UK
->Lancashire
->->Burnley
->->Blackburn
->Merseyside
->->Liverpool
->West Yorkshre
->->Leeds
->->York
在php中我会做类似的事情:
while($row = $rec->fetch_object()) {
$var[$row->country]['county'][$row->county]['city'][$row->city] = $row->city;
}
i have a sql query that returns 3 levels of a data chain on each row (ie. Country, County, City). There may be more than 1 county per country and more than 1 city per county.
resultset:
"UK" "Lancashire" "Burnley"
"UK" "Lancashire" "Blackburn"
"UK" "Merseyside" "Liverpool"
"UK" "West Yorkshire" "Leeds"
"UK" "West Yorkshire" "York"
how do i iterate the resultset in python to create something like:
UK
->Lancashire
->->Burnley
->->Blackburn
->Merseyside
->->Liverpool
->West Yorkshre
->->Leeds
->->York
in php i would do something like:
while($row = $rec->fetch_object()) {
$var[$row->country]['county'][$row->county]['city'][$row->city] = $row->city;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这并不理想,因为它有点晦涩难懂。
可能有更干净的方法来做到这一点。
This isn't ideal because it's kind of obscure.
There are probably cleaner ways to do this.