2016-11-30 82 views
3

我想在下面的分项数据结构来检索top trackPython的 - 寻找最上层的项目在字典

tracks = { 
u'Harry Patch (In Memory Of)': {u'playlist1': 4.0}, 
u'Fake Plastic Trees': {u'playlist2': 5.0, u'playlist1': 6.0}, 
u'The Man Who Sold The World': {u'playlist1': 3.0}, 
u'Running Up That Hill': {u'playlist1': 2.0}, 
u"Jeep's Blues": {u'playlist3': 1.0, u'playlist4':9.0}, 
u'Stella By Starlight': {u'playlist3': 1.0}, 
u'Codex': {u'playlist1': 3.0} 
} 

的逻辑如下:

1 - 找到属于多轨道一个播放列表。

2 - 在这些结果中,找到此曲目的最高排名。 (添加单个播放列表居)

我部分有这个片段:

tracks = [i[0] for i in radio.items()] 
playlists = [i[1] for i in radio.items()] 

ranking = [] 

for p in playlists: 
    name = p.keys() 
    rank = p.values() 
    if len(rank) >= 2: 
     ranks = sum(r for r in rank) 
     ranking.append(ranks) 

print max(ranking) 

它打印:11.0,这相当于所需的输出u'Fake Plastic Trees

,但我已经失去了跟踪(原谅我的双关语)的track name

如何使用上面的代码检索曲目名称?

ps。有没有更简单的方法来实现我想要的结果?

回答

1

虽然@Tim已经解决了你的代码是如何工作的,我可以解决如何缩短这一点。不必跟踪您的歌曲和歌曲名称,只需创建另一个词典来使用两个或更多播放列表来保存所有曲目。从那里,你可以使用内置函数max()和简单lambda得到与在dict()最高值的关键:其中产量

tracks = { 
u'Harry Patch (In Memory Of)': {u'playlist1': 4.0}, 
u'Fake Plastic Trees': {u'playlist2': 5.0, u'playlist1': 6.0}, 
u'The Man Who Sold The World': {u'playlist1': 3.0}, 
u'Running Up That Hill': {u'playlist1': 2.0}, 
u"Jeep's Blues": {u'playlist3': 1.0, u'playlist4':9.0}, 
u'Stella By Starlight': {u'playlist3': 1.0}, 
u'Codex': {u'playlist1': 3.0} 
} 

def get_top_track(tracks): 
    # create a dict to hold 
    # the top keys. 
    ranks = {} 
    for key, val in tracks.items(): 
    if len(val) >= 2: 
     # only add the tracks 
     # which have two or 
     # more playlists. 
     total = sum(el for el in val.values()) 
     ranks[key] = total 
    # lastly, use the builtin in function max() 
    # and a lambda to get the key with the highest value 
    # in the ranks dict. 
    return max(ranks, key=lambda key: ranks[key]) 

print(get_top_track(tracks)) 

>>> u'Fake Plastic Trees' 
2

默认情况下,当使用for循环时,仅迭代字典的值。你可以使用iteritems()以及按键:

tracks = [i[0] for i in radio.items()] 
playlists = [i[1] for i in radio.items()] 

ranking = [] 
songs = [] 

for song, p in playlists.iteritems(): 
    name = p.keys() 
    rank = p.values() 
    if len(rank) >= 2: 
     ranks = sum(r for r in rank) 
     ranking.append(ranks) 
     songs.append(song) 

import numpy as np 
song_index = np.argmax(ranking) 
print songs[song_index] 
0
>>> top_track = max(tracks, key=lambda k: len(tracks[k])) 
>>> top_track 

u'Fake塑料树'