使用列表和词典

2024-09-29 21:59:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个清单:

list = [
    {'album': '1', 'artist': 'pedro', 'title': 'Duhast'},
    {'album': '2', 'artist': 'hose', 'title':'Star boy'},
    {'album': '1', 'artist': 'migel', 'title': 'Lemon tree'}
]

我需要这样对列表进行分组/排序:

list = [
    {'album': '1', 
     'tracks': [
        {'artist': 'pedro', 'title': 'Duhast'},
        {'artist': 'migel', 'title': 'Lemon tree'}]
    },
    {'album': '2',
     'tracks':[
        {'artist': 'hose', 'title':'Star boy'}]
    }
]

更确切地说,我需要按专辑对曲目进行分组。有什么办法让这件事简单些吗?你知道吗


Tags: tree列表album排序titleartistliststar
1条回答
网友
1楼 · 发布于 2024-09-29 21:59:17

1-衬里:)

from itertools import groupby

list = [{'album': '1', 'artist': 'pedro', 'title': 'Duhast'}, {'album': '2', 'artist': 'hose', 'title':'Star boy'}, {'album': '1', 'artist': 'migel', 'title': 'Lemon tree'}]

res = [{'album': album, 'tracks': [{'artist': track['artist'], 'title': track['title']} for track in tracks]} for album, tracks in groupby(sorted(list, key=lambda x: x['album']), lambda x: x['album'])]

print(res)

https://repl.it/HA48/2

正如@Prune提到的,groupby函数可用于按指定的键函数对列表进行分组。为了使其工作,列表必须按键排序。你知道吗

就我个人而言,我觉得上面的解决方案有点难以理解。。。这会产生相同的结果:

from itertools import groupby

list = [{'album': '1', 'artist': 'pedro', 'title': 'Duhast'}, {'album': '2', 'artist': 'hose', 'title':'Star boy'}, {'album': '1', 'artist': 'migel', 'title': 'Lemon tree'}]

res = []
for album, tracks in groupby(sorted(list, key=lambda x: x['album']), lambda x: x['album']):
  res.append({'album': album, 'tracks': [{'artist': track['artist'], 'title': track['title']} for track in tracks]})

print(res)

https://repl.it/HA48/1

相关问题 更多 >

    热门问题