Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python – แปลง Matrix (List of Lists) เป็น Dictionary Value List

ภาพรวม

แปลง matrix (list of lists) ให้เป็น dictionary ที่ key คือ row number (1-based) และ value คือ row list

ตัวอย่างโค้ด


my_list = [[71, 26, 35], [65, 56, 37], [89, 96, 99]]
print("The list is:", my_list)

# Dictionary comprehension
my_result = {i + 1: my_list[i] for i in range(len(my_list))}

print("The result is:", my_result)

ผลลัพธ์

The list is: [[71, 26, 35], [65, 56, 37], [89, 96, 99]]
The result is: {1: [71, 26, 35], 2: [65, 56, 37], 3: [89, 96, 99]}

วิธีอื่นๆ


# ใช้ enumerate (Pythonic กว่า)
my_result = {i: row for i, row in enumerate(my_list, 1)}

# ใช้ dict() + enumerate
my_result = dict(enumerate(my_list, 1))

# 0-based index
my_result = {i: row for i, row in enumerate(my_list)}
# {0: [71, 26, 35], 1: [65, 56, 37], 2: [89, 96, 99]}

Pandas DataFrame -> Dict


import pandas as pd
df = pd.DataFrame(my_list)
# orient='index' -> key=row index, value=list
my_result = df.to_dict(orient='index')
# {0: {0: 71, 1: 26, 2: 35}, 1: {0: 65, 1: 56, 2: 37}, ...}

# orient='list' -> key=col index, value=column list
my_result = df.to_dict(orient='list')

กรณี Matrix ไม่เท่ากัน (Jagged Array)

Dictionary comprehension ยังทำงานได้ เพราะแต่ละ row เป็น list อิสระ