【问题标题】:Error in returning dictionary items as string? (python)将字典项目作为字符串返回时出错? (Python)
【发布时间】:2022-01-14 14:18:27
【问题描述】:

我有一个具有空字典属性的类:

class Library:
    def __init__(self,library):
        self.library={}
    
    def addSong(self,title,artist,genre,playCount):
        for i in self.library.keys():
            if i == title:
                x=self.library.get(title)
                x[2]= x[2]+1
            else:    
                self.library[title]=[artist,genre,playCount]
    
    def song2String(self,title):
        x=self.library.get(title)
        return f"{x[0]} {title} ({x[1]}), {x[2]}" 

现在当我这样做时:

m1= Library({})
m1.addSong("Saturday Night's Alright for Fighting","Elton John","Rock",22)

代码运行正常,项目被添加到m1 字典中。 但是当我输入这个时:

print(m1.song2String("Saturday Night's Alright for Fighting"))

我收到此错误消息:

return f"str{x[0]} str{title} (str{x[1]}), str{x[2]}" 
TypeError: 'NoneType' object is not subscriptable

我的语法错误是什么?

【问题讨论】:

  • self.library.get(title) 正在返回None,这表明title 不是self.library 中的键,或者self.library[title] 处的值是None
  • 确定要加+1而不是+playcount?,比如用22调用两次,应该是23还是44?
  • "代码运行正常,项目被添加到 m1 字典中。" 你确定?你怎么知道的?

标签: python class dictionary syntax


【解决方案1】:

我想这是你所期望的。在这里的addsong函数中, 首先我检查字典中是否有可用的键。如果是真的, 迭代并做你想做的事。否则,添加第一个字典项 到字典。在 song2string 方法中,首先你要 确定字典的工作原理。在这种情况下,key 是一个字符串,而 值是字典中的列表。那么你可以返回你想要的 使用字典。

class Library:
    def __init__(self,library=dict()):
        self.library=library
    
    def addSong(self,title,artist,genre,playCount):
        
        if len(self.library.keys())>0:
            for i in self.library.keys():
                if i == title:
                    x=self.library.get(title)
                    x[2]= x[2]+1
        else:    
            self.library[title]=[artist,genre,playCount]
            # print(self.library)
    
    def song2String(self,title):
        x=self.library
        print(x)
        return x[title][0], x[title][1], x[title][2]
    
m1= Library()
m1.addSong("Saturday Night's Alright for Fighting","Elton John","Rock",22)
print(m1.song2String("Saturday Night's Alright for Fighting"))

【讨论】:

    【解决方案2】:

    您当前的代码返回无,这是您的错误的原因。我不知道你为什么要循环插入歌曲,直接使用字典:

    class Library:
        def __init__(self,library):
            self.library={}
        
        def addSong(self,title,artist,genre,playCount):
            if title in self.library:   ## changed code here and below
                x=self.library.get(title)
                x[2]= x[2]+1
            else:    
                self.library[title]=[artist,genre,playCount]
        
        def song2String(self,title):
            x=self.library.get(title)
            return f"{x[0]} {title} ({x[1]}), {x[2]}" 
    

    输出:

    m1= Library({})
    m1.addSong("Saturday Night's Alright for Fighting","Elton John","Rock",22)
    print(m1.library)
    # {"Saturday Night's Alright for Fighting": ['Elton John', 'Rock', 22]}
    
    print(m1.song2String("Saturday Night's Alright for Fighting"))
    # Elton John Saturday Night's Alright for Fighting (Rock), 22
    

    【讨论】:

      【解决方案3】:

      您在 library 键上进行迭代:for i in self.library.keys(),但由于没有,所以什么也没做,使其工作的最小更改是

      def addSong(self, title, artist, genre, playCount):
          for i in self.library.keys():
              if i == title:
                  x = self.library.get(title)
                  x[2] = x[2] + 1
                  break
          else:
              self.library[title] = [artist, genre, playCount]
      

      但最好只是测试标题是否存在,然后做正确的事情。

      def addSong(self, title, artist, genre, playCount):
          if title in self.library:
              self.library[title][2] += playCount
          else:
              self.library[title] = [artist, genre, playCount]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-16
        相关资源
        最近更新 更多