【问题标题】:how to print a list that is in a dictionary, as a string in python? And how to edit the list's elements?如何将字典中的列表打印为python中的字符串?以及如何编辑列表的元素?
【发布时间】:2022-01-14 12:40:27
【问题描述】:

我有一个具有字典属性的类。字典有歌曲标题作为它的键和一个包含艺术家、流派和 playCount 的列表,如下所示:

class library:
def __init__(self,library):
    self.library={}
def addSong(self,title,artist,genre,playCount):
    self.library[title]=[artist,genre,playCount]

playCount 是一个整数。如何在不更改任何其他元素的情况下将 1 添加到 playCount 元素。我是为它创建一个新功能还是可以在不创建功能的情况下做到这一点?另外,我怎样才能创建一个函数来将字典的键和值打印为这样的字符串:

artist, title (genre), playCount

【问题讨论】:

    标签: python list class dictionary key-value


    【解决方案1】:

    IIUC,您只想在每次将现有标题传递给addSong 时增加playCount,对吗?

    您可以在addSong 中输入if-else 条件来检查title 是否在self.library 中,如果存在,则只需将键title 的值的最后一个元素递增@987654327 @。

    此外,要打印,只需将项目分配到正确的位置:

    class library:
        def __init__(self):
            self.library = {}
        
        def addSong(self, title, artist, genre, playCount=1):
            if title in self.library:
                self.library[title][-1] += playCount
            else:
                self.library[title] = [artist, genre, playCount]
                
        def get_song_data(self, title):
            if title in self.library:
                x = self.library[title] + [title]
                return "{0}, {3} ({1}), {2}".format(*x)
    
    lib = library()
    

    输出:

    lib.addSong('Easy on Me','Adele','ballad',10)
    print(lib.get_song_data('Easy on Me'))         # Adele, Easy on Me (ballad), 10
    
    lib.addSong('Easy on Me','Adele','ballad',2)
    print(lib.get_song_data('Easy on Me'))         # Adele, Easy on Me (ballad), 12
    
    lib.addSong('Easy on Me','Adele','ballad')
    print(lib.get_song_data('Easy on Me'))         # Adele, Easy on Me (ballad), 13
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-10
      • 2019-07-31
      • 1970-01-01
      • 2014-11-30
      • 2022-11-04
      • 2020-04-09
      • 1970-01-01
      • 2020-09-18
      相关资源
      最近更新 更多