У меня есть этот список списков:

music = [[u'Charles Bradley', u'Heart of Gold'], [u'Charles Bradley', u'Stay Away'], [u'Iron & Wine', u'Pagan Angel And A Borrowed Car'], [u'Iron & Wine', u'White Tooth Man'], [u'Iron & Wine', u'Lovesong of the Buzzard'], [u'Iron & Wine', u'Carousel'], [u'Iron & Wine', u'House By The Sea'], [u'Iron & Wine', u'Innocent Bones'], [u'Iron & Wine', u"Wolves (Song of the Shepherd's Dog)"], [u'Iron & Wine', u'Resurrection Fern'], [u'Iron & Wine', u'Boy With a Coin'], [u'Iron & Wine', u'The Devil Never Sleeps'], [u'Iron & Wine', u'Peace Beneath The City'], [u'Iron & Wine', u'Flightless Bird, American Mouth'], [u'Animal Collective', u'In the Flowers'], [u'Animal Collective', u'My Girls'], [u'Animal Collective', u'Also Frightened'], [u'Animal Collective', u'Summertime Clothes'], [u'Animal Collective', u'Daily Routine'], [u'Animal Collective', u'Bluish'], [u'Animal Collective', u'Guys Eyes'], [u'Animal Collective', u'Taste'], [u'Animal Collective', u'Lion in a Coma'], [u'Animal Collective', u'No More Runnin'], [u'Animal Collective', u'Brother Sport'], [u'Richard Hawley', u'I Still Want You'], [u'Richard Hawley', u'The World Looks Down'], [u'Richard Hawley', u'Which Way'], [u'Richard Hawley', u'Serenade Of Blue'], [u'Richard Hawley', u'Long Time Down'], [u'Richard Hawley', u'Nothing Like A Friend'], [u'Richard Hawley', u'Sometimes I Feel'], [u'Richard Hawley', u'Tuesday pm'], [u'Richard Hawley', u'Welcome The Sun'], [u'Richard Hawley', u'Heart Of Oak'], [u'Richard Hawley', u'What Love Means'], [u'Suuns', u'Powers of Ten'], [u'Suuns', u'2020'], [u'Suuns', u'Minor Work'], [u'Suuns', u'Mirror Mirror'], [u'Suuns', u"Edie's Dream"], [u'Suuns', u'Sunspot'], [u'Suuns', u'Bambi'], [u'Suuns', u'Holocene City'], [u'Suuns', u'Images du Futur'], [u'Suuns', u"Music Won't Save You"], [u'Deerhunter', u'Earthquake'], [u'Deerhunter', u'Don\u2019t Cry'], [u'Deerhunter', u'Revival'], [u'Deerhunter', u'Sailing'], [u'Deerhunter', u'Memory Boy'], [u'Deerhunter', u'Desire Lines'], [u'Deerhunter', u'Basement Scene'], [u'Deerhunter', u'Helicopter'], [u'Deerhunter', u'Fountain Stairs'], [u'Deerhunter', u'Coronado'], [u'Deerhunter', u'He Would Have Laughed'], [u'Animal Collective', u'FloriDada'], [u'Animal Collective', u'Hocus Pocus'], [u'Animal Collective', u'Vertical'], [u'Animal Collective', u'Lying in the Grass'], [u'Animal Collective', u'The Burglars'], [u'Animal Collective', u'Natural Selection'], [u'Animal Collective', u'Bagels in Kiev'], [u'Animal Collective', u'On Delay'], [u'Animal Collective', u'Spilling Guts'], [u'Animal Collective', u'Summing the Wretch'], [u'Animal Collective', u'Golden Gal'], [u'Animal Collective', u'Recycling'], [u'Elvis Costello & The Attractions', u'Uncomplicated'], [u'Elvis Costello & The Attractions', u"I Hope You're Happy Now"], [u'Elvis Costello & The Attractions', u'Tokyo Storm Warning'], [u'Elvis Costello & The Attractions', u'Home Is Anywhere You Hang Your Head'], [u'Elvis Costello & The Attractions', u'I Want You'], [u'Elvis Costello & The Attractions', u'Honey Are You Straight Or Are You Blind'], [u'Elvis Costello & The Attractions', u'Blue Chair'], [u'Elvis Costello & The Attractions', u'Battered Old Bird'], [u'Elvis Costello & The Attractions', u'Crimes Of Paris'], [u'Elvis Costello & The Attractions', u'Poor Napoleon'], [u'Elvis Costello & The Attractions', u'Next Time Round']]

И я хотел бы закончить со списком словарей, где каждый уникальный исполнитель является key, а его список треков - value, например так:

dicts = [{'Charles Bradley: ['Heart of Gold', 'Stay Away']}, ...]]

Для этого я зашел так далеко:

artists = set()
dicts=[]

for item in music:
    artists.add(item[0])
    for artist in artists:
        if artist in item:
            dicts[artist]=item[1]

Что явно недостаточно далеко, потому что я получаю:

{u'Suuns': u"Music Won't Save You", u'Animal Collective': u'Recycling', u'Iron & Wine': u'Flightless Bird, American Mouth', u'Deerhunter': u'He Would Have Laughed', u'Charles Bradley': u'Stay Away', u'Elvis Costello & The Attractions': u'Next Time Round', u'Richard Hawley': u'What Love Means'}

Любая помощь приветствуется.

1
user7830303 28 Авг 2017 в 22:26

4 ответа

Лучший ответ

Вы можете использовать defaultdict:

from collections import defaultdict

d = defaultdict(list)

for artist, song in music:
   d[artist].append(song)

full_list = [{a:b} for a, b in d.items()]

Выход:

[{u'Suuns': [u'Powers of Ten', u'2020', u'Minor Work', u'Mirror Mirror', u"Edie's Dream", u'Sunspot', u'Bambi', u'Holocene City', u'Images du Futur', u"Music Won't Save You"]}, {u'Animal Collective': [u'In the Flowers', u'My Girls', u'Also Frightened', u'Summertime Clothes', u'Daily Routine', u'Bluish', u'Guys Eyes', u'Taste', u'Lion in a Coma', u'No More Runnin', u'Brother Sport', u'FloriDada', u'Hocus Pocus', u'Vertical', u'Lying in the Grass', u'The Burglars', u'Natural Selection', u'Bagels in Kiev', u'On Delay', u'Spilling Guts', u'Summing the Wretch', u'Golden Gal', u'Recycling']}, {u'Iron & Wine': [u'Pagan Angel And A Borrowed Car', u'White Tooth Man', u'Lovesong of the Buzzard', u'Carousel', u'House By The Sea', u'Innocent Bones', u"Wolves (Song of the Shepherd's Dog)", u'Resurrection Fern', u'Boy With a Coin', u'The Devil Never Sleeps', u'Peace Beneath The City', u'Flightless Bird, American Mouth']}, {u'Deerhunter': [u'Earthquake', u'Don\u2019t Cry', u'Revival', u'Sailing', u'Memory Boy', u'Desire Lines', u'Basement Scene', u'Helicopter', u'Fountain Stairs', u'Coronado', u'He Would Have Laughed']}, {u'Charles Bradley': [u'Heart of Gold', u'Stay Away']}, {u'Elvis Costello & The Attractions': [u'Uncomplicated', u"I Hope You're Happy Now", u'Tokyo Storm Warning', u'Home Is Anywhere You Hang Your Head', u'I Want You', u'Honey Are You Straight Or Are You Blind', u'Blue Chair', u'Battered Old Bird', u'Crimes Of Paris', u'Poor Napoleon', u'Next Time Round']}, {u'Richard Hawley': [u'I Still Want You', u'The World Looks Down', u'Which Way', u'Serenade Of Blue', u'Long Time Down', u'Nothing Like A Friend', u'Sometimes I Feel', u'Tuesday pm', u'Welcome The Sun', u'Heart Of Oak', u'What Love Means']}]
3
Ajax1234 28 Авг 2017 в 19:28
from collections import defaultdict

d = defaultdict(list)
songs = [[u'Charles Bradley', u'Heart of Gold'], [u'Charles Bradley', u'Stay Away'], [u'Iron & Wine', u'Pagan Angel And A Borrowed Car'], [u'Iron & Wine', u'White Tooth Man'], [u'Iron & Wine', u'Lovesong of the Buzzard'], [u'Iron & Wine', u'Carousel'], [u'Iron & Wine', u'House By The Sea'], [u'Iron & Wine', u'Innocent Bones'], [u'Iron & Wine', u"Wolves (Song of the Shepherd's Dog)"], [u'Iron & Wine', u'Resurrection Fern'], [u'Iron & Wine', u'Boy With a Coin'], [u'Iron & Wine', u'The Devil Never Sleeps'], [u'Iron & Wine', u'Peace Beneath The City'], [u'Iron & Wine', u'Flightless Bird, American Mouth'], [u'Animal Collective', u'In the Flowers'], [u'Animal Collective', u'My Girls'], [u'Animal Collective', u'Also Frightened'], [u'Animal Collective', u'Summertime Clothes'], [u'Animal Collective', u'Daily Routine'], [u'Animal Collective', u'Bluish'], [u'Animal Collective', u'Guys Eyes'], [u'Animal Collective', u'Taste'], [u'Animal Collective', u'Lion in a Coma'], [u'Animal Collective', u'No More Runnin'], [u'Animal Collective', u'Brother Sport'], [u'Richard Hawley', u'I Still Want You'], [u'Richard Hawley', u'The World Looks Down'], [u'Richard Hawley', u'Which Way'], [u'Richard Hawley', u'Serenade Of Blue'], [u'Richard Hawley', u'Long Time Down'], [u'Richard Hawley', u'Nothing Like A Friend'], [u'Richard Hawley', u'Sometimes I Feel'], [u'Richard Hawley', u'Tuesday pm'], [u'Richard Hawley', u'Welcome The Sun'], [u'Richard Hawley', u'Heart Of Oak'], [u'Richard Hawley', u'What Love Means'], [u'Suuns', u'Powers of Ten'], [u'Suuns', u'2020'], [u'Suuns', u'Minor Work'], [u'Suuns', u'Mirror Mirror'], [u'Suuns', u"Edie's Dream"], [u'Suuns', u'Sunspot'], [u'Suuns', u'Bambi'], [u'Suuns', u'Holocene City'], [u'Suuns', u'Images du Futur'], [u'Suuns', u"Music Won't Save You"], [u'Deerhunter', u'Earthquake'], [u'Deerhunter', u'Don\u2019t Cry'], [u'Deerhunter', u'Revival'], [u'Deerhunter', u'Sailing'], [u'Deerhunter', u'Memory Boy'], [u'Deerhunter', u'Desire Lines'], [u'Deerhunter', u'Basement Scene'], [u'Deerhunter', u'Helicopter'], [u'Deerhunter', u'Fountain Stairs'], [u'Deerhunter', u'Coronado'], [u'Deerhunter', u'He Would Have Laughed'], [u'Animal Collective', u'FloriDada'], [u'Animal Collective', u'Hocus Pocus'], [u'Animal Collective', u'Vertical'], [u'Animal Collective', u'Lying in the Grass'], [u'Animal Collective', u'The Burglars'], [u'Animal Collective', u'Natural Selection'], [u'Animal Collective', u'Bagels in Kiev'], [u'Animal Collective', u'On Delay'], [u'Animal Collective', u'Spilling Guts'], [u'Animal Collective', u'Summing the Wretch'], [u'Animal Collective', u'Golden Gal'], [u'Animal Collective', u'Recycling'], [u'Elvis Costello & The Attractions', u'Uncomplicated'], [u'Elvis Costello & The Attractions', u"I Hope You're Happy Now"], [u'Elvis Costello & The Attractions', u'Tokyo Storm Warning'], [u'Elvis Costello & The Attractions', u'Home Is Anywhere You Hang Your Head'], [u'Elvis Costello & The Attractions', u'I Want You'], [u'Elvis Costello & The Attractions', u'Honey Are You Straight Or Are You Blind'], [u'Elvis Costello & The Attractions', u'Blue Chair'], [u'Elvis Costello & The Attractions', u'Battered Old Bird'], [u'Elvis Costello & The Attractions', u'Crimes Of Paris'], [u'Elvis Costello & The Attractions', u'Poor Napoleon'], [u'Elvis Costello & The Attractions', u'Next Time Round']]
for artist, title  in songs:
    d[artist].append(title)

print(d)
2
Solaxun 28 Авг 2017 в 19:30

Я думаю, что вы делаете слишком много работы. Набор на самом деле не понадобится, потому что вы можете просто проверить, есть ли ключ в словаре с ключевым словом "in". Если бы я был тобой, я бы вместо этого взял исполнителя, проверил, есть ли исполнитель в словаре, и, если это так, добавил бы его в список песен этого исполнителя.

for item in music:
    artistExists=False
    for dict in dicts:
        if item[0] in dict:
            dict[item[0]].append(item[1])
            artistExists=True
            break
    if not artistExists:
        dict.append({item[0]: [item[1]]})

(defaultdict хорошо работает здесь, но я хотел бы дать ответ без него)


Заметьте, почему конкретно вы хотите список диктов? Это может быть намного проще для понимания, создания и реализации, когда это делается с помощью единого слова.

dict={}
for item in music:
    if item[0] not in dict:
        dict[item[0]] = []
    dict[item[0]].append(item[1])      

Который оставил бы вас с:

{'Charles Bradley': ['Heart of Gold', 'Stay Away'], 'Iron & Wine': ['Lovesong of the Buzzard', 'White Tooth Man'], ...} 
0
RageCage 28 Авг 2017 в 19:49

Альтернатива без defaultdict:

dicts = {}

for key, value in music:
    if key not in dicts:
        dicts[key] = []
    dicts[key].append(value) 

После этого вы можете использовать подход full_list @ Ajax1234.

1
atru 28 Авг 2017 в 19:45