按唯一值分组列表

时间:2017-04-07 15:03:54

标签: python list python-3.x sorting

我有一个清单

list = [{'album': 'Spring Times', 'artist': 'Momo Pulse'}, {'album': 'Spring Times', 'artist': 'K.oshkin'}, {'album': 'Damn ', 'artist': 'Florent B'}]

我想将其分组以获取:

list = [{'album': 'Spring Times', 'artist1': 'Momo Pulse', 'artist2': 'K.oshkin'}, {'album': 'Damn ', 'artist1': 'Florent B'}]

我该怎么做? 有什么想法吗?

3 个答案:

答案 0 :(得分:0)

from itertools import groupby

# input
my_list = [{'album': 'Spring Times', 'artist': 'Momo Pulse'}, {'album': 'Spring Times', 'artist': 'K.oshkin'}, {'album': 'Damn ', 'artist': 'Florent B'}]

# Have a function to return the merged dictionary after an update
def merge_dict(a, b):
    a.update(b)
    return a

# key function for sort and groupby
sortkey = lambda d: d['album']

# Sort and group by album
my_groups = groupby(sorted(my_list, key=sortkey), key=sortkey)

# Generate output
print [merge_dict({'album':k},{'artist'+str(i+1):d['artist'] for i, d in enumerate(g)}) for k, g in my_groups]  

答案 1 :(得分:-1)

from collections import defaultdict

l = [{'album': 'Spring Times', 'artist': 'Momo Pulse'}, 
     {'album': 'Spring Times', 'artist': 'K.oshkin'}, 
     {'album': 'Damn ', 'artist': 'Florent B'}]
d = defaultdict(list)

for record in l:
    d[record['album']].append(record['artist'])

我们现在有一个词典,将专辑名称映射到艺术家名单。

final = []

for album, artists in d.items():
    temp = {'album': album}
    for i, x in enumerate(artists, start=1):
        temp['artist{}'.format(i)] = x
    final.append(temp)

print(final)

打印

[{'album': 'Damn ', 'artist1': 'Florent B'}, {'album': 'Spring Times', 'artist1': 'Momo Pulse', 'artist2': 'K.oshkin'}]

答案 2 :(得分:-1)

l = [{'album': 'Spring Times', 'artist': 'Momo Pulse'}, {'album': 'Spring Times', 'artist': 'K.oshkin'}, {'album': 'Damn ', 'artist': 'Florent B'}]

albums = {}
for el in l:
    album = albums.setdefault(el['album'], {})
    artist_id = sum(1 for k in album if k.startswith('artist'))
    album['artist'+str(artist_id)] = el['artist']

l2 = albums.values() #This is your output