【问题标题】:Python append replaces the existing list with NonePython append 将现有列表替换为 None
【发布时间】:2018-03-26 06:03:37
【问题描述】:

请看看这个程序。

append 函数将列表替换为 None。错误附在下面

class Solution(object):
     def isIsomorphic(self, a, b):

        ad = {} 
        bd = {}
        if len(a) != len(b):
             return False 
        for i in range(len(a)):
             if a[i] in ad:
                 ad[a[i]] = ad[a[i]].append(i)  
            else:
                ad[a[i]] = [i]

            if b[i] in bd:
                 bd[b[i]] = bd[b[i]].append(i)           
            else:
                 bd[b[i]] = [i]
         ret = True 
         for j,k in zip(ad.values(), bd.values()):
             if j != k:
                return False 
         return ret 


sol = Solution()
print sol.isIsomorphic("ccc", "aab")  
错误
     ad[a[i]] = ad[a[i]].append(i)

 AttributeError: 'NoneType' object has no attribute 'append'     

【问题讨论】:

    标签: python list dictionary data-structures append


    【解决方案1】:

    append 将值附加到列表并返回None。所以ad[a[i]] = ad[a[i]].append(i) 意味着你正在用None 替换ad[a[i]]

    Here 是说明它的文档的一部分

    您可能已经注意到插入、删除或排序等方法 只修改列表没有打印返回值——它们返回 默认无。 [1] 这是所有可变数据的设计原则 Python 中的结构。

    【讨论】:

      【解决方案2】:

      给你:你将 ad[a[i]].append[i] 分配给 ad[a[i]],这是不需要的。这是函数调用并返回无。你只需要做 ad[a[i]].append(i)

      class Solution(object):
       def isIsomorphic(self, a, b):
      
          ad = {} 
          bd = {}
          if len(a) != len(b):
               return False 
          for i in range(len(a)):
              if a[i] in ad:
                   ad[a[i]].append(i)  
              else:
                  ad[a[i]] = [i]
      
      
              if b[i] in bd:
                   bd[b[i]].append(i)           
              else:
                   bd[b[i]] = [i]
          ret = True 
          for j,k in zip(ad.values(), bd.values()):
              if j != k:
                  return False 
          return ret 
      

      sol = 解决方案() 打印 sol.isIsomorphic("ccc", "aab")

      【讨论】:

        猜你喜欢
        • 2021-10-23
        • 2019-05-29
        • 2017-08-06
        • 1970-01-01
        • 2018-05-19
        • 2013-10-27
        • 1970-01-01
        • 2016-06-29
        • 2012-04-14
        相关资源
        最近更新 更多