Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.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列表时出现问题_Python_List_Concatenation - Fatal编程技术网

连接Python列表时出现问题

连接Python列表时出现问题,python,list,concatenation,Python,List,Concatenation,我正在尝试通过以下操作连接两个列表,一个仅包含一个元素: print([6].append([1,1,0,0,0])) 但是,Python返回None。我做错了什么?使用+运算符 >>> [6] + [1,1,0,0,0] [6, 1, 1, 0, 0, 0] 您试图做的是将一个列表附加到另一个列表上,这将导致 >>> [6].append([1,1,0,0,0]) [6, [1,1,0,0,0]] 您之所以看到返回的None,是因为.append具有破

我正在尝试通过以下操作连接两个列表,一个仅包含一个元素:

print([6].append([1,1,0,0,0]))
但是,Python返回
None
。我做错了什么?

使用+运算符

>>> [6] + [1,1,0,0,0]
[6, 1, 1, 0, 0, 0]
您试图做的是将一个列表附加到另一个列表上,这将导致

>>> [6].append([1,1,0,0,0])
[6, [1,1,0,0,0]]
您之所以看到返回的
None
,是因为
.append
具有破坏性,修改原始列表,并返回
None
。它不会返回要附加到的列表。因此,您的列表正在被修改,但您正在打印函数的输出
。append

首先使用列表(除非您确实不想在将来使用数据)

另一种方法是使用
extend()
而不是
append()


对于列表连接,您有两个选项:

newlist = list1 + list2

list1.extend(list2)

后者修改列表,前者创建新列表。在一些情况下,这是一个显著的差异。我喜欢将extend作为求和的替代方法,但我否决了这个答案,因为extend的结果与append的结果不同,尽管在你的答案中,你假装这是获得相同结果的另一种方法。。。
>>> a=[6]
>>> a.extend([1,1,0,0,0])
>>> a
[6, 1, 1, 0, 0, 0]
newlist = list1 + list2

list1.extend(list2)
l1 = [6]
l2 = [1, 1, 0, 0, 0]
l1.extend(l2)
print l1
[6, 1, 1, 0, 0, 0]