Below are three lists which I would like to combine into a single nested list:
List_1=[1,2,3]
List_2=[4,5,6]
List_3=[7,8,9]
My attempt:
List_x=[]
List_x.append(List_1)
List_x.append(List_2)
List_x.append(List_3)
print List_x
Result:
[[1,2,3],[4,5,6],[7,8,9]]
Desired result: Same as the result I got, but the approach is extremely slow given the size of my actual data.
If you need a nested list (list of list), Concat them like this:
>>> 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]]
If you want a flattened combined list, useitertools.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]
If memory space is a problem, you can use 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]]
If you want a flattened list and memory is a problem, use 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]
Nested list:
>>> 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]]
Merged list:
>>> 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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.