2017-08-03 131 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

相关问题