'NoneType'对象没有属性'append'python

时间:2017-10-05 05:13:42

标签: python

我运行以下代码:

import sys
def find_common(a,b,c):
    d=[]
    for i in a:
        if i in b:
            d=d.append(i)
    for i in d:
        if i not in c:
            c=c.append(i)
    print(c)
    return c

if __name__ == '__main__':
    a=[1,1,2,4]
    b=[2,2,3,4]
    c=[]
    find_common(a,b,c)
    sys.exit()

但收到以下错误:

d=d.append(i)  
AttributeError: 'NoneType' object has no attribute 'append' 

为什么会这样?请帮忙解决。

4 个答案:

答案 0 :(得分:2)

d.append(i)返回None
因此:
d = d.append(i)None分配给d

将该行替换为:
d.append(i)

c = c.append(i)

也是如此

答案 1 :(得分:1)

首先,您不需要重新分配d

// MARK: Resume Data

/**
    Creates a request for downloading from the resume data produced from a previous request cancellation.

    If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.

    - parameter resumeData:  The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask` 
                             when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for 
                             additional information.
    - parameter destination: The closure used to determine the destination of the downloaded file.

    - returns: The created download request.
*/
public func download(_ resumeData: Data, destination: Request.DownloadFileDestination) -> Request {
    return download(.resumeData(resumeData), destination: destination)
}

答案 2 :(得分:1)

我不会重复其他人在append()返回None时已经说过的内容,但我会建议一个更短的解决方案,它可以使用任意数量的参数:

def find_common(*args):
    return list(set.intersection(*[set(arg) for arg in args]))

>>> a = [1, 3, 2, 4]
>>> b = [2, 2, 3, 4]
>>> c = [3, 3, 4, 5]
>>> d = [1, 4, 7, 6]
>>> find_common(a, b, c, d)
[4]

答案 3 :(得分:0)

问题在于您将d.append()重新分配给d。

d.append()返回None。

d = []
print d.append(4) #None

因此,请将您的代码更改为以下内容,然后才能生效。

def find_common(a,b,c):
    d=[]
    for i in a:
        if i in b:
            d.append(i)
    for i in d:
        if i not in c:
            c.append(i)
    print(c)
    return c