Computer >> Máy Tính >  >> Lập trình >> Python

Python - Cách làm phẳng danh sách 2D

Danh sách là một tập hợp được sắp xếp và có thể thay đổi. Trong Python, danh sách được viết bằng dấu ngoặc vuông. Bạn truy cập các mục trong danh sách bằng cách tham chiếu đến số chỉ mục. Lập chỉ mục phủ định có nghĩa là bắt đầu từ cuối, -1 đề cập đến mục cuối cùng. Bạn có thể chỉ định một phạm vi chỉ mục bằng cách chỉ định nơi bắt đầu và nơi kết thúc phạm vi. Khi chỉ định một phạm vi, giá trị trả về sẽ là một danh sách mới với các mục được chỉ định.

Ví dụ

# using chain.from_iterables
# import chain
from itertools import chain
ini_list = [[1, 2, 3],
   [3, 6, 7],
   [7, 5, 4]]    
# printing initial list
print ("initial list ", str(ini_list))
# converting 2d list into 1d
# using chain.from_iterables
flatten_list = list(chain.from_iterable(ini_list))
# printing flatten_list
print ("final_result", str(flatten_list))
# using list comprehension
# import chain
from itertools import chain  
ini_list = [[1, 2, 3],
   [3, 6, 7],
   [7, 5, 4]]            
# printing initial list
print ("initial list ", str(ini_list))  
# converting 2d list into 1d
# using list comprehension
flatten_list = [j for sub in ini_list for j in sub]
# printing flatten_list
print ("final_result", str(flatten_list))
# using functools.reduce  
# import functools
from functools import reduce  
ini_list = [[1, 2, 3],
   [3, 6, 7],
   [7, 5, 4]]              
# printing initial list
print ("initial list ", str(ini_list))  
# converting 2d list into 1d
# using functools.reduce
flatten_list = reduce(lambda z, y :z + y, ini_list)  
# printing flatten_list
print ("final_result", str(flatten_list))
# using sum  
ini_list = [[1, 2, 3],
   [3, 6, 7],
   [7, 5, 4]]  
# printing initial list
print ("initial list ", str(ini_list))  
# converting 2d list into 1d
flatten_list = sum(ini_list, [])  
# printing flatten_list
print ("final_result", str(flatten_list))
ini_list=[[1, 2, 3],
   [3, 6, 7],
   [7, 5, 4]]
#Using lambda  
flatten_list = lambda y:[x for a in y for x in flatten_list(a)] if type(y) is list else [y]
print("Initial list ",ini_list)
#priniting initial list  
print("Flattened List ",flatten_list(ini_list))
# printing flattened list

Đầu ra

('initial list ', '[[1, 2, 3], [3, 6, 7], [7, 5, 4]]')
('final_result', '[1, 2, 3, 3, 6, 7, 7, 5, 4]')
('initial list ', '[[1, 2, 3], [3, 6, 7], [7, 5, 4]]')
('final_result', '[1, 2, 3, 3, 6, 7, 7, 5, 4]')
('initial list ', '[[1, 2, 3], [3, 6, 7], [7, 5, 4]]')
('final_result', '[1, 2, 3, 3, 6, 7, 7, 5, 4]')
('initial list ', '[[1, 2, 3], [3, 6, 7], [7, 5, 4]]')
('final_result', '[1, 2, 3, 3, 6, 7, 7, 5, 4]')
('Initial list ', [[1, 2, 3], [3, 6, 7], [7, 5, 4]])
('Flattened List ', [1, 2, 3, 3, 6, 7, 7, 5, 4])