生成字典键和值集的随机组合

时间:2019-04-01 01:38:36

标签: python dictionary

我正在创建一个程序来对音乐库文件进行排序。我有一个特别的功能,generateRandomPlaylist(musicLibDictionary),我一直坚持。

该函数需要从字典中随机选择一个键,并将值之一随机分配给该键。例如,词典中的艺术家包括The Who,Adele和The Beatles。各自的专辑包括汤米; 19、21、25;修道院路,随它吧。我需要程序随机选择一个键(艺术家),然后随机选择一个键的值。随机生成的播放列表需要具有所有三位歌手,而不是重复歌手,而是与歌手不同的专辑。按照我的设置方式,输出不一定使用全部三个艺术家。示例输出应如下所示:

Here is your random playlist:
- 25 by Adele
- Abbey Road by The Beatles
- Tommy by The Who

每次调用该函数时,播放列表都应该不同。就像我说的那样,现在该功能无法正常运行,并且我还收到一个打印错误,提示我无法连接列表和字符串,所以我不知道我要去哪里。

该程序的代码如下:

# importing pickle
import pickle
import random

# declaration of functions
def displayMenu():
    print("Welcome to Your Music Library")
    print("Options:")
    print("\t1) Display Library")
    print("\t2) Display all artists")
    print("\t3) Add an album")
    print("\t4) Delete an album")
    print("\t5) Delete an artist")
    print("\t6) Search Library")
    print("\t7) Generate a random playlist")
    print("\t8) Make your own playlist")
    print("\t9) Exit")

def displayLibrary(musicLibDictionary):
    for key in musicLibDictionary:
        print("Artist: " + key)
        print("Albums: ")
        for album in musicLibDictionary[key]:
            print("\t- " + album)

def displayArtists(musicLibDictionary):
    print("Displaying all artists:")
    for key in musicLibDictionary:
        print(" - " + key)

def addAlbum(musicLibDictionary):
    artistName = input("Please enter the name of the artist you would like to add: ")
    albumName = input("Please enter the name of the album you would like to add: ")
    if artistName in musicLibDictionary.keys():
        musicLibDictionary[artistName].append(albumName)
    else:
        musicLibDictionary[artistName] = [albumName]

def deleteAlbum(musicLibDictionary):
    artist = input("Enter artist: ")
    albumToBeDeleted = input("Enter album: ")
    if artist in musicLibDictionary.keys():
        if albumToBeDeleted in musicLibDictionary[artist]:
            musicLibDictionary[artist].remove(albumToBeDeleted)
            return True
        else:
            return False
    else:
        return False

def deleteArtist(musicLibDct):
    artistToBeDeleted = input("Enter artist to delete: ")
    if artistToBeDeleted in musicLibDct.keys():
        del musicLibDct[artistToBeDeleted]
        return True
    else:
        return False

def searchLibrary(musicLibDictionary):
    searchTerm = input("Please enter a search term: ")
    searchTerm = searchTerm.lower()
    print("Artists containing" + searchTerm)
    for key in musicLibDictionary.keys():
        if searchTerm.lower() in key.lower():
            print("\t - ", end="")
            print(key)
    print("Albums containing" + searchTerm)
    for album in musicLibDictionary[key]:
        print("\t- " + album)

    for key in musicLibDictionary.keys():
        for album in musicLibDictionary[key]:
            if searchTerm in album.lower():
                print("\t - ", end="")
                print(album)

def generateRandomPlaylist(musicLibDictionary):
    print("Here is your random playlist:")
    for artist in musicLibDictionary.keys():
        artistSelection = random.choice(list(musicLibDictionary.keys()))
        albumSelection = random.choice(list(musicLibDictionary.values()))
    print("\t-" + albumSelection + "by" + artistSelection)


def loadLibrary(libraryFileName):
    fileIn = open(libraryFileName, "rb")
    val = pickle.load(fileIn)
    val = dict(val)
    return val

def saveLibrary(libraryFileName, musicLibDictionary):
    fileIn = open(libraryFileName, "wb")
    pickle.dump(musicLibDictionary, fileIn)

def main():
    musicLib = loadLibrary("musicLibrary.dat")
    userChoice = ""
    while (userChoice != 7):
        displayMenu()
        userChoice = int(input("> "))
        if userChoice == 1:
            displayLibrary(musicLib)
        elif userChoice == 2:
            displayArtists(musicLib)
        elif userChoice == 3:
            addAlbum(musicLib)
        elif userChoice == 4:
            deleteAlbum(musicLib)
        elif userChoice == 5:
            deleteArtist(musicLib)
        elif userChoice == 6:
            searchLibrary(musicLib)
        elif userChoice == 7:
            generateRandomPlaylist(musicLib)
        elif userChoice == 8:
            saveLibrary("musicLibrary.dat", musicLib)


# Call main
main()

1 个答案:

答案 0 :(得分:1)

这是一种实现方式,如果我正确理解您希望每个艺术家随机地一次获得一次,并希望从每个艺术家那里随机获得一张专辑

def generateRandomPlaylist(musicLibDictionary):
    print("Here is your random playlist:")
    artists = list(musicLibDictionary.keys())
    random.shuffle(artists)  # Perform an in-place shuffle
    for artistSelection in artists:
        albumSelection = random.choice(list(musicLibDictionary[artistSelection]))
        print("\t-" + albumSelection + "by" + artistSelection)

我们知道我们只希望所有艺术家一次,但顺序随机。由于字典的键是艺术家,因此我们只需在键上执行random.shuffle即可随机获得艺术家的顺序。然后,我们必须查看每位艺术家的专辑(musicLibDictionary[artist])并制作一个random.choice,以便随机挑选一张专辑。

您的代码逐行执行的操作如下

def generateRandomPlaylist(musicLibDictionary):
    print("Here is your random playlist:")
    for artist in musicLibDictionary.keys(): # For each artist
        artistSelection = random.choice(list(musicLibDictionary.keys()))  # Choose one artist randomly (not necessarily the one in your for loop)
        albumSelection = random.choice(list(musicLibDictionary.values()))  # Choose a random album list (musicLibDictionary.values() returns a list of lists, so you're just choosing a random discography (list) from a random artist)
    print("\t-" + albumSelection + "by" + artistSelection)  # Because this is not indented into your loop, you're likely only getting the last one chosen

添加字符串和列表(在python中不允许直接使用,必须先将列表强制转换为字符串)时出现问题,原因是您的albumSelection变量是来自随机艺术家,甚至不一定是artistSelection变量中的艺术家。您的musicLibDictionary.values()返回的内容类似[['Tommy'], ['19', '21', '25'], ['Abbey Road', 'Let It Be']]random.choice从提供给它的列表中选择一个随机值,因此给定列表[[1,2,3], [4,5,6]],它可以选择[1,2,3]