【问题标题】:How do I get certain things removed and printed out in a Dictionary?如何在字典中删除和打印某些内容?
【发布时间】:2014-04-27 21:49:02
【问题描述】:

我正在做家庭作业,但我不知道如何从字典中删除歌曲,以及如何获得仅打印歌曲列表中的艺术家的功能?

pl=[]
    song ={"song":"Baby","artist":"Justin Bieber","duration":220,"genre":"pop"}

    pl.append(song)

    def printPlaylist(pl):
        for i in range (0,len(pl)):
            play = pl [i]
            print("song-",play["song"])
            print("artist-",play["artist"])
            print("duration-",play["duration"])
            print("genre-",play["genre"])
            print("---")
    print("raw list")
    printPlaylist(pl)

    def addSong(pl,song,artist,duration,genre="pop"):
        pl.append ({"song":title,"artist":singer,"duration":time,"genre":kind})

    def removeSongs(pl,song):
        title = ("Enter a song")
        if song in pl:
            del song[title]
        else:
            print = ("Song not in list")

    def listByArtist(pl):
         listByArtist = sorted(listByArtist,key=pl

【问题讨论】:

    标签: loops python-3.x dictionary


    【解决方案1】:

    要获取字典的特定值,请通过其键调用它:

    song ={"song":"Baby","artist":"Justin Bieber","duration":220,"genre":"pop"}
    artist = song["artist"]
    print artist #Justin Bieber
    

    从字典中删除到底是什么意思?

    【讨论】:

    • 如何从字典中删除歌曲。谢谢你帮助我。
    • 你的意思是从字典song中删除"song":"Baby"
    • 这正是它所要求的“从播放列表中删除歌曲。您将删除所有在歌曲中传递子字符串的歌曲。因此,如果用户使用“by”调用该函数,它将例如删除歌曲“Baby”。打印一条消息,指示用户是否成功删除了歌曲或歌曲是否不在播放列表中。”
    【解决方案2】:

    要从歌曲列表(而不是字典)中删除歌曲,您需要这样:

    def removeSongs(pl, song):
        removed_indices = []
        for ix, s in enumerate(pl):
            if s["song"] == song:
                removed_indices.append(ix)
        for i in removed_indices:
            del pl[i]
        return True if removed_indices else False
    

    那么你可以这样使用它:

    title = raw_input("Enter song title to remove: ")
    smth_was_removed = removeSongs(playlist, title)
    if not smth_was_removed:
        print("No such song")
    else:
        print("All songs with that title were removed")
    

    此外,del 不适合在列表中使用;如果你想从列表中删除一个项目,你需要知道它的索引:

    >>> a = ["Erik", "John", "Mary"]
    >>> del a[1]  # deletes "John"
    >>> a
    ["Erik", "Mary"]
    

    在字典上,它是这样工作的:

    >>> x = {"a": 1, "b": 2, "c": 3}
    >>> del x["b"]
    >>> x
    {"a": 1, "c": 3}
    

    【讨论】:

      猜你喜欢
      • 2021-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-27
      相关资源
      最近更新 更多