0

这是我的代码

def printList(stringlist):
    empty = []
    if stringlist is None:
        print empty
    else:
        print stringlist

def add (stringlist, string):
    string = [] if string is None else string
    if stringlist is not None:
        stringlist.insert(0, string)
    else:
        stringlist.append(1)

它以某种方式出现“AttributeError:'NoneType'对象没有属性'append'”

我最初是在寻找这样运行的代码:

>>> myList = None
>>> printList(myList)
[]
>>> for word in ['laundry','homework','cooking','cleaning']:
myList = add(myList, word)
printList(myList)
[laundry]
[homework, laundry]
[cooking, homework, laundry]
[cleaning, cooking, homework, laundry]
4

3 回答 3

1

正如其他人已经指出的那样,问题是在您的else情况下,列表是None. 但这只是问题的一部分。而不是追加到None,您必须在else案例中创建一个新列表,但是您还必须添加到return列表中,因为您不再stringlist就地编辑。

无论如何,您应该(并且似乎期望)返回列表,否则mylistNone在您执行myList = add(myList, word)循环之后。

此外,您的行string = [] if string is None else string有点奇怪,因为如果字符串是None.

我建议你改变你的add方法是这样的:

def add (stringlist, string):
    item = [] if string is None else [string]
    return item + (stringlist or [])

这会将字符串包装在一个列表中(如果字符串是 ,则创建一个空列表None)并返回一个由该字符串和旧列表构造的新列表(如果该列表是 ,则返回另一个空列表None)。(a or b等价于a if a else b)。同样,您printList可以简化为:

def printList(stringlist):
    print stringlist or []
于 2013-10-28T09:52:01.953 回答
1

You're trying to call append method from None object:

if stringlist is not None:
    stringlist.insert(0, string)
else:
    # stringlist is None
    # Well, let's append to it!
    stringlist.append(1) 
于 2013-10-28T04:52:43.623 回答
1
if stringlist is not None:
    stringlist.insert(0, string)
else:
    stringlist.append(1)

When stringlist is not None, you insert something, but when it is None (else clause), you are appending something to it. You cannot append something to stringlist because it's None.

于 2013-10-28T04:52:43.810 回答