下面是我想要组合成一个嵌套列表的三个列表:
List_1=[1,2,3]
List_2=[4,5,6]
List_3=[7,8,9]
我的尝试:
List_x=[]
List_x.append(List_1)
List_x.append(List_2)
List_x.append(List_3)
print List_x
结果:
[[1,2,3],[4,5,6],[7,8,9]]
期望的结果:与我得到的结果相同,但考虑到实际数据的大小,这种方法非常慢。
答案 0 :(得分:9)
如果你需要一个嵌套列表(列表列表),Concat就像这样:
>>> l1 = [1,2,3]
>>> l2 = [4,5,6]
>>> l3 = [7,8,9]
>>> l123 = [l1,l2,l3]
>>> l123
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
如果您想要一个展平的组合列表,请使用itertools.chain
:
>>> l1 = [1,2,3]
>>> l2 = [4,5,6]
>>> l3 = [7,8,9]
>>> from itertools import chain
>>> list(chain(*[l1,l2,l3]))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
如果内存空间有问题,您可以使用append
:
>>> l1 = [[1,2,3]]
>>> l1.append([4,5,6])
>>> l1.append([7,8,9])
>>> l1
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
如果您想要一个扁平列表并且内存有问题,请使用extend
:
>>> l1 = [1,2,3]
>>> l1.extend([4,5,6])
>>> l1.extend([7,8,9])
>>> l1
[1, 2, 3, 4, 5, 6, 7, 8, 9]
答案 1 :(得分:0)
嵌套列表:
>>> list_1 = [1, 2, 3]
>>> list_2 = [4, 5, 6]
>>> list_3 = [7, 8, 0]
>>> nested = [list_1, list_2, list_3]
>>> nested
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
合并列表:
>>> list_1 = [1, 2, 3]
>>> list_2 = [4, 5, 6]
>>> list_3 = [7, 8, 9]
>>> merged = list_1 + list_2 + list_3
>>> merged
[1, 2, 3, 4, 5, 6, 7, 8, 9]