Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python中的list.append()返回null_Python - Fatal编程技术网

python中的list.append()返回null

python中的list.append()返回null,python,Python,python中list1.append()和list1+list2之间的实际区别是什么?? 同时,为什么下面的语句返回NULL print(list1.append(list2)) {其中list1和list2是2个简单列表}list.append()修改对象并返回None []+[]创建并“返回”新列表 建议阅读:返回None是一种传达操作有副作用的方式,即它正在更改操作数之一,而不是保持操作数不变并返回新值 list1.append(list2) …更改列表1,使其成为此类别的成员

python中list1.append()和list1+list2之间的实际区别是什么?? 同时,为什么下面的语句返回NULL

print(list1.append(list2))
{其中list1和list2是2个简单列表}

list.append()
修改对象并返回None

[]+[]
创建并“返回”新列表


建议阅读:

返回
None
是一种传达操作有副作用的方式,即它正在更改操作数之一,而不是保持操作数不变并返回新值

list1.append(list2)
…更改列表1,使其成为此类别的成员


比较以下两段代码:

# in this case, it's obvious that list1 was changed
list1.append(list2)
print list1
……和:

# in this case, you as a reader don't know if list1 was changed,
# unless you already know the semantics of list.append.
print list1.append(list2)

禁止后者(通过使其无用)从而提高语言的可读性。

打印函数时,打印它返回的内容,而append方法不返回任何内容。但是,您的列表现在有了一个新元素。您可以打印列表以查看所做的更改

>>> a = [1,2,3]
>>> b = [4,5,6]
>>> a.append(b) # append just appends the variable to the next index and returns None
>>> print a
[1,2,3,[4,5,6]]
>>> a.extend(b) # Extend takes a list as input and extends the main list
[1,2,3,4,5,6]
>>> a+b # + is exactly same as extend
[1,2,3,4,5,6]
list1+list2
表示将两个列表合并为一个大列表

list1.append(element)
在列表末尾添加一个元素

下面是一个append vs的示例+

>>> a = [1,2,3]
>>> b = [4,5,6]
>>> a + b
[1, 2, 3, 4, 5, 6]
>>>
>>> a.append(b)
>>> a
[1, 2, 3, [4, 5, 6]]

请注意,
.append
与将两个列表添加在一起有很大的不同,但是
.extend
将一个列表逐个添加更为相似,只是它会改变原始列表,而不是返回新列表。