gpt4 book ai didi

python - 如何将数据放入 TreeView 中?

转载 作者:太空宇宙 更新时间:2023-11-03 19:09:22 24 4
gpt4 key购买 nike

我在 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)中,使其看起来像这样:

  • 麦当娜
    • 光线
      • 爱情的替代品
      • 卡住
    • 需要记住的事情
      • 你会看到
    • 睡前故事
      • secret
  • U2
    • 约书亚树
      • 街道所在的地方..
      • 我还没有...
    • 阿赫东宝贝
      • 一个
      • 直到结束..

我不知道如何以这种方式编码:我想到了嵌套循环,但我找不到解决方案。有人用任何语言研究过此查询的解决方案吗?如果不需要代码,我就需要逻辑。然后任何人都可以使用自己的编程语言来实现它。

最佳答案

您可以使用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)

关于python - 如何将数据放入 TreeView 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13545979/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com