Python 使用列表和字典

Python 使用列表和字典,python,list,python-3.x,Python,List,Python 3.x,我有一份清单: list = [ {'album': '1', 'artist': 'pedro', 'title': 'Duhast'}, {'album': '2', 'artist': 'hose', 'title':'Star boy'}, {'album': '1', 'artist': 'migel', 'title': 'Lemon tree'} ] 我需要按如下方式对列表进行分组/排序: list = [ {'album': '1',

我有一份清单:

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'}]
    }
]
更准确地说,我需要按专辑对曲目进行分组。有什么办法让这变得简单吗?

1-liner:)

正如@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)

您尝试过哪些不适合您的方法?我们通常希望您在寻求帮助之前自己编写一些代码。在您这样做时,请查看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)