我在 python 列表中有一个数据表,数据如下所示:
[
{Artist='Madonna', album='Ray of Light', title='Substitute for love'},
{Artist='Madonna', album='Ray of Light', title='Frozen'},
{Artist='Madonna', album='Something to remember', title='You'll see'},
{Artist='Madonna', album='Bedtime stories', title='Secret'},
{Artist='U2', album='The Joshua Tree', title='Where the streets have no name'},
{Artist='U2', album='The Joshua Tree', title='I still haven'ts found...'},
{Artist='U2', album='The Joshua Tree', title='With or without you'},
{Artist='U2', album='Acthung Baby', title='One'},
{Artist='U2', album='Acthung Baby', title='Until the end of the world'}
]
我想将它放入 TreeView (特别是 QTreeWidget)中,使其看起来像这样:
我不知道如何以这种方式编码:我想到了嵌套循环,但我找不到解决方案。有人用任何语言研究过此查询的解决方案吗?如果不需要代码,我就需要逻辑。然后任何人都可以使用自己的编程语言来实现它。
您可以使用nested defaultdicts 将记录列表转换为嵌套字典。 .
from collections import defaultdict
data = [ {'Artist':'Madonna', 'album':'Ray of Light', 'title':'Substitute for love'},
....
{'Artist':'U2', 'album':'Acthung Baby', 'title':'Until the end of the world'}
]
tree_data = defaultdict(lambda: defaultdict(list))
for d in data:
tree_data[d['Artist']][d['album']].append(d['title'])
一旦您获得此表单中的数据,就可以轻松地以您需要的格式打印它。
以下是针对您的示例的简单方法:
for artist in tree_data.keys():
print(artist)
for album, titles in tree_data[artist].iteritems():
print("\t" + album)
for title in titles:
print ("\t\t" + title)
我是一名优秀的程序员,十分优秀!