【问题标题】:Python TypeError: descriptor 'append' for 'list' objects doesn't apply to a 'int' objectPython TypeError:“list”对象的描述符“append”不适用于“int”对象
【发布时间】:2020-06-30 04:26:28
【问题描述】:

我正在尝试解决 Python 中的 LeetCode 问题。给定一个整数列表和一个目标,我们必须在列表中找到所有唯一的整数组合,其总和等于目标。该列表可以有重复的整数,但整数的组合(其和等于目标)在结果中必须是唯一的。该列表将只有正整数https://leetcode.com/problems/combination-sum-ii/

下面是代码:

class Solution:
    def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
        result = List[List[int]]
        c = List[int]
        self.combSum2(0,sorted(candidates),target,result,c)
        return result

    def combSum2(self, i: int, l: List[int], t: int, res: List[List[int]], curr: List[int]):
        if t == 0:
            print(curr)
            res.append(curr)
            return
        if t < 0:
            return
        for idx in range(i,len(l):
            if(idx == i or l[idx] != l[idx-1]):
                curr.append(l[idx])
                self.combSum2(idx+1,l,t-l[idx],res,curr)
                del curr[-1] 

代码确实产生了独特的组合,但是,当我运行它时,我收到了这个错误: TypeError: descriptor 'append' for 'list' objects doesn't apply to a 'int' objectcurr.append(l[idx]) 线上。

如何解决这个问题?任何帮助将不胜感激。

编辑:

我已经尝试了 @user2357112 支持的 Monica 建议并更改了我的代码:

class Solution:
    def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
        result = []
        c = []
        self.combSum2(0,sorted(candidates),target,result,c)
        print("result:")
        print(result)
        return result

    def combSum2(self, i: int, l: List[int], t: int, res: [], curr: []):
        if t == 0:
            print(curr)
            res.append(curr)
            return
        if t < 0:
            return
        for idx in range(i,len(l)):
            if(idx == i or l[idx] != l[idx-1]):
                curr.append(l[idx])
                self.combSum2(idx+1,l,t-l[idx],res,curr)
                del curr[-1]

现在错误消失但结果为空:

[1, 1, 6]
[1, 2, 5]
[1, 7]
[2, 6]
result:
[[], [], [], []]

正在创建组合,但没有附加到结果中。

我不知道错误在哪里。任何帮助,将不胜感激。谢谢。

【问题讨论】:

  • 这是整个错误信息吗? result = List[List[int]] 是干什么用的?
  • result 用于存储来自candidates 的整数的所有唯一组合。使用错误消息编辑问题。 @AMC
  • result = List[List[int]] 不会使 result 成为整数列表的列表。如果您想要一个空列表,请使用[]List[List[int]] 是用于类型注释的东西。
  • @user2357112supportsMonica 更新了我的问题。
  • 是的,你有更多的错误。 (此外,您也不应该将类型注释更改为 []。)

标签: python python-3.x


【解决方案1】:

如果您在list python 类型(类)而不是list 的实例上调用append 方法,则会发生此问题。

>>> from typing import List
>>> l = list
>>> l.append
<method 'append' of 'list' objects>
>>> l.append(3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: descriptor 'append' requires a 'list' object but received a 'int'
>>> 

如您所见,append 的第一个参数是 list (self) 类型的对象

class list(object):
    """
    Built-in mutable sequence.
    
    If no argument is given, the constructor creates a new empty list.
    The argument must be an iterable if specified.
    """
    def append(self, *args, **kwargs): # real signature unknown
        """ Append object to the end of the list. """
        pass

【讨论】:

    【解决方案2】:

    你可能正在使用deque,一旦我也遇到了同样的问题, 错误是因为:您直接附加到deque(如果您正在使用它)而不初始化列表。

    容易出错的代码

    from collections import defaultdict, deque
    d = defaultdict(lambda: deque)
    a = [1, 2, 3]
    for i in range(3):
       d[a[i]].append(i)
    

    无错误代码

    from collections import defaultdict, deque
    d = defaultdict(lambda: deque([])
    

    在前面的错误中查看它不适用于 int 对象,实际上它不适用于任何东西,直到您在 deque 中声明了一个列表。

    总的来说, 总是声明为deque([])

    【讨论】:

      猜你喜欢
      • 2021-07-01
      • 2022-11-26
      • 2021-09-14
      • 2020-03-18
      • 2022-01-21
      • 2020-11-01
      • 2021-10-26
      • 1970-01-01
      • 2020-08-12
      相关资源
      最近更新 更多