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

Python - รวมเมทริกซ์ตามสมาชิกของคอลัมน์แรก


เมื่อต้องการรวมเมทริกซ์ตามสมาชิกของคอลัมน์แรก ใช้การวนลูปง่าย list comprehension และเมธอด 'setdefault'

ตัวอย่าง

สาธิตด้านล่าง:

my_list = [[41, "python"], [13, "pyt"], [41, "is"], [4, "always"], [3, "fun"]] 
print("The list is :") 
print(my_list) 
my_result = {} 
for key, value in my_list: 
    my_result.setdefault(key, []).append(value) 
my_result = [[key] + value for key, value in my_result.items()] 
print("The result is :") 
print(my_result)

ผลลัพธ์

The list is : [[41, 'python'], [13, 'pyt'], [41, 'is'], [4, 'always'], [3, 'fun']] 
The result is : [[41, 'python', 'is'], [13, 'pyt'], [4, 'always'], [3, 'fun']]

คำอธิบาย

  • กำหนดลิสต์และแสดงผล
  • สร้าง dictionary ว่าง
  • วนลูปลิสต์ รวม key-value ที่มี key เดียวกัน append เข้า dictionary
  • ใช้ list comprehension ดึง element ของ dictionary รวม key และ value
  • กำหนดให้ตัวแปร
  • แสดงผลลัพธ์บนคอนโซล