3 回答
TA贡献1827条经验 获得超4个赞
def getMoods(user, users, songs):
userSongs = users[user] # songs this user listens to
moods = {} # count of each mood this user listens to
for song in userSongs:
for mood in songs[song]: # for each mood of that song
moods.setdefault(mood, 0)
moods[mood] += 1
return max(moods, key=moods.get) # the most prevalent mood
for user in users:
print(user, 'likes', getMoods(user, users, songs)) # mood with the highest count
TA贡献1846条经验 获得超7个赞
您实际上并没有使用Counter
并尝试调用most_common
列表。让我们尝试将其分解:
创建一个新字典,并为每个用户找到其相关的情绪(总体)。
从该词典中找到每个用户最常见的情绪。
为了更好地处理 1,我们可以使用defaultdict
:
from collections import Counter, defaultdict
Users_moods = defaultdict(list)
for user, songs in Users.items():
for song in songs:
Users_moods[user].extend(Songs[song])
common_moods = {user: Counter(moods).most_common(1)[0][0] for user, moods in Users_moods.items()}
print(Users_moods)
print(common_moods)
这给出:
defaultdict(<class 'list'>, {'User1': ['techno', 'upbeat', 'rock', 'upbeat', 'rap', 'upbeat'], 'User2': ['pop', 'sad', 'rock', 'sad'], 'User3': ['rock', 'upbeat', 'rock', 'sad']})
{'User1': 'upbeat', 'User2': 'sad', 'User3': 'rock'}
common或者,您可以使用相同的循环动态构建字典,为Counter每个用户创建一个单独的字典:
common_moods = {}
for user, songs in Users.items():
User_moods = Counter()
for song in songs:
User_moods += Counter(Songs[song])
common_moods[user] = User_moods.most_common(1)[0][0]
print(common_moods)
TA贡献1864条经验 获得超2个赞
如果您打算使用 collections.Counter,让我们看看https://docs.python.org/3/library/collections.html#collections.Counter您将需要
mood_counter = Counter(iterable)
据推测,这里的可迭代来自于查看一个用户,然后是他们的所有歌曲,然后是这些歌曲的所有情绪。我们不要尝试制作一个衬垫,而是正常地迭代这些衬垫。
def get_user_mood(user, Users, Songs):
accumulated_moods = []
for song_name in Users[user]:
moods_for_this_song = Songs[song_name]
accumulated_moods.extend(moods_for_this_song)
mood_counter = Counter(accumulated_moods)
return mood_counter.most_common(1)[0][0] # validate?
这使您可以在理解中相当轻松地构建字典
Users_moods = {user: get_user_mood(user, Users, Songs) for user in Users}
添加回答
举报