Giới thiệu
Để chuyển ma trận (list of lists) thành dictionary nơi key là chỉ số hàng (bắt đầu từ 1) và value là list hàng đó, dùng dictionary comprehension.
Ví dụ minh họa
my_list = [[71, 26, 35], [65, 56, 37], [89, 96, 99]]
print("Ma trận:")
print(my_list)
my_result = {my_index + 1: my_list[my_index] for my_index in range(len(my_list))}
print("Dictionary kết quả:")
print(my_result)
Kết quả đầu ra
Ma trận:
[[71, 26, 35], [65, 56, 37], [89, 96, 99]]
Dictionary kết quả:
{1: [71, 26, 35], 2: [65, 56, 37], 3: [89, 96, 99]}
Giải thích
range(len(my_list))sinh index 0,1,2.- Key = index+1, Value = my_list[index].
- Dictionary comprehension tạo dict trong một dòng.