在python中加入两个列表后,如何创建列表列表列表?

在python中加入两个列表后,如何创建列表列表列表?,python,python-3.x,list,Python,Python 3.x,List,我有两个列表,我正在尝试加入他们,期望的是一个列表列表。 你能提出同样的建议吗? 我也尝试过使用+运算符和append list_output_first = [] list_output_second = [] list_a = [1,2,[]] list_b = ['a',['b', '']] list_output_first = list_a + list_b list_output_first = list_a.append(list_b) 输出 [1, 2, [], ['a

我有两个列表,我正在尝试加入他们,期望的是一个列表列表。 你能提出同样的建议吗? 我也尝试过使用+运算符和append

list_output_first = []
list_output_second = []
list_a = [1,2,[]]
list_b = ['a',['b', '']]

list_output_first = list_a + list_b 

list_output_first = list_a.append(list_b)

输出

[1, 2, [], ['a', ['b', '']]]
预期的

[[1, 2, []], ['a', ['b', '']]]

您需要构建一个主列表,其中包含另外两个:

list_output_first = [list_a, list_b] 
或将其构建为空,并添加其他两个:

list_output_first = []
list_output_first.append(list_a)
list_output_first.append(list_b) 

Reference在上面的两个示例解决方案中,您都会传递列表本身,因此如果您稍后修改
list\u a
list\u b
,您也会首先修改
list\u output\u中的更改。如果您想先在
list\u output\u中获得列表的副本
do

list_output_first = [list(list_a), list(list_b)] 
# and for the other: 
list_output_first.append(list(list_a))

列表的
+
运算符将它们相加,形成一个包含每个元素的列表,您需要一个额外的容器,将这两个列表放在一个列表中,而不是它们的值,只需执行以下操作:

list_output_first = [list_a, list_b]

可以这样做:

list_output_first = [list_a] + [list_b]
只需将两个列表放在一个列表中,即可添加它们


有很多方法,这里我分享两种我觉得简单的方法。 第一种方法:-您可以将列表b扩展为列表a并打印列表a。如果要将其存储在另一个列表中,则可以创建另一个列表,并存储扩展其他列表的列表副本

list_a = [1, 2, []]
list_b = ['a', ['b', '']]
list_a.extend(list_b)
list_c = list_a.copy()
print(list_c)
第二种方法:-您可以添加这两个列表并将其存储在空列表中

list_a = [1, 2, []]
list_b = ['a', ['b', '']]
list_c = list_a + list_b
print(list_c)

希望它能有所帮助。

如果您希望列表不带与元素的反向引用连接,它是由以下元素组成的:

from copy import deepcopy
answer = [ item for item in (deepcopy(list_a), deepcopy(list_b)) ] 

list_output_first=[list_a,list_b]你能解释一下使用+,append和你的方法有什么区别吗。使用[list_a,list_b]?@TanayGupta添加一些文本。你只需要知道,用2个列表来表示它们,你需要一个额外的列表来表示它们
from copy import deepcopy
answer = [ item for item in (deepcopy(list_a), deepcopy(list_b)) ]