2017-08-03 117 views

回答

2

你可以使用加法:

>>> a=[5, 'str1'] 
>>> b=[8, 'str2'] + a 
>>> b 
[8, 'str2', 5, 'str1'] 
+0

這絕對是最好的選擇。謝謝 – bigboat

9

使用extend()

b.extend(a) 
[8, 'str2', 5, 'str1'] 
0

您可以在任意位置使用切片解包內的另一個列表的列表:

>>> a=[5, 'str1'] 
>>> b=[8, 'str2'] 
>>> b[1:1] = a 
>>> b 
[8, 5, 'str1', 'str2'] 

>>> a=[5, 'str1'] 
>>> b=[8, 'str2'] 
>>> b[2:2] = a # inserts and unpacks `a` at position 2 (the end of b) 
>>> b 
[8, 'str2', 5, 'str1'] 

同樣你也可以在其它位置插入

1
>>> a 
[5, 'str1'] 
>>> b=[8, 'str2'] + a 
>>> b 
[8, 'str2', 5, 'str1'] 
>>> 

延長()您需要定義B和A單獨...

然後b.extend(a)將工作

2

的有效的方式做到這與擴展( )列表類的方法。它需要迭代作爲參數並將其元素附加到列表中。

b.extend(a) 

在內存中創建新列表的其他方法是使用+運算符。

b = b + a 
+1

這絕對是更好的解決方案。 – Kshitij

相關問題