เมื่อสร้างแมทริกซ์ใน Python บางครั้งเราต้องการควบคุมจำนวนครั้งที่แต่ละองค์ประกอบปรากฏ บทความนี้จะแสดง 2 วิธี: ใช้ zip() และใช้ map() ร่วมกับ operator.mul
วิธีที่ 1: ใช้ zip()
ประกาศลิสต์องค์ประกอบ และลิสต์จำนวนครั้งที่ต้องการให้ซ้ำ ใช้ zip() จับคู่แล้ววนลูปสร้างลิสต์ย่อย
ตัวอย่างโค้ด
listA = ['m', 'n', 'p', 'q']
elem_count = [1, 0, 3, 2]
print("Given List of elements: ", listA)
print("Count of elements: ", elem_count)
# สร้างแมทริกซ์ด้วย zip
res = [[x] * y for x, y in zip(listA, elem_count)]
print("The new matrix is: ", res)
ผลลัพธ์
Given List of elements: ['m', 'n', 'p', 'q'] Count of elements: [1, 0, 3, 2] The new matrix is: [['m'], [], ['p', 'p', 'p'], ['q', 'q']]
วิธีที่ 2: ใช้ map() และ operator.mul
ใช้ mul จากโมดูล operator ร่วมกับ map() จะได้ผลลัพธ์เป็นสตริงที่รวมตัวอักษรซ้ำกัน (ไม่ใช่ลิสต์ย่อย)
ตัวอย่างโค้ด
from operator import mul
listA = ['m', 'n', 'p', 'q']
elem_count = [1, 0, 3, 2]
print("Given List of elements: ", listA)
print("Count of elements: ", elem_count)
# สร้างแมทริกซ์ด้วย map และ mul
res = list(map(mul, listA, elem_count))
print("The new matrix is: ", res)
ผลลัพธ์
Given List of elements: ['m', 'n', 'p', 'q'] Count of elements: [1, 0, 3, 2] The new matrix is: ['m', '', 'ppp', 'qq']
สรุป: วิธี zip() ให้ผลลัพธ์เป็นลิสต์ของลิสต์ (โครงสร้างแมทริกซ์จริง) ส่วน map(mul) ให้ผลลัพธ์เป็นลิสต์ของสตริงที่รวมตัวอักษร เลือกใช้ตามรูปแบบข้อมูลที่ต้องการ