簡體   English   中英

a = list()。append(“hello”)vs a = list(); 在python中a.append(“你好”)?

[英]a=list().append(“hello”) vs a=list(); a.append(“hello”) in python?

我有

try:
    a = list().append('hello')

但是aNoneType

try:
    b = list()
    b.append('hello')

blist類型

我認為list()返回一個列表對象, list().append('hello')將使用返回列表做追加,但為什么是價值a None

list()確實返回一個空列表( [] ),但append方法在就地列表上運行 - 它更改列表本身,並且不返回新列表。 它返回None

例如:

>>> lst = []
>>> lst.append('hello')  # appends 'hello' to the list
>>> lst
['hello']
>>> result = lst.append('world')  # append method returns None
>>> result  # nothing is displayed
>>> print result
None
>>> lst  # the list contains 'world' as well now
['hello', 'world']
a = list().append('hello')

上面一行,將創建一個新的列表,然后調用append()方法,只是返回代碼存儲append()給變量a 由於值為None ,因此只表示append()方法沒有返回值。

要確認這一點,您可以嘗試這樣做:

>>> a = list()
>>> result = a.append('hello')
>>> print a
['hello']
>>> print result
None

你已經得到了問題的答案,但我只是指出,做你想要做的事情的最好辦法是。 它應該是:

a = [ 'hello' ]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM