python如何合并两个列表的内容?
如果我直接
list1.append(list2)
我发现list2作为一个单个的整体,append到了list1。而list成了列表的列表。
但是我又不想:
for l in list2:
list1.append(1)
这样一个一个插入。
有没有函数能合并这两个列表的?
[解决办法]
list1 += list2
[解决办法]
try it. list1.extend(list2)
[解决办法]
Python 3.2.3 (default, Apr 11 2012, 07:15:24) [MSC v.1500 32 bit (Intel)] on win32Type "copyright", "credits" or "license()" for more information.>>> A = [1, 2, 3]>>> B = [4, 5, 6]>>> A1 = A[:]>>> A.append( B )>>> print( A )[1, 2, 3, [4, 5, 6]]>>> A = A1[:]>>> print( A )[1, 2, 3]>>> A += B>>> print( A )[1, 2, 3, 4, 5, 6]>>>
[解决办法]
用extend()
区别
Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32Type "copyright", "credits" or "license()" for more information.>>> A = [1, 2, 3]>>> B = [4, 5, 6]>>> A+B[1, 2, 3, 4, 5, 6]>>> A.extend(B)>>> A[1, 2, 3, 4, 5, 6]>>> A.append(B)>>> A[1, 2, 3, 4, 5, 6, [4, 5, 6]]>>>