โจทย์: ให้ลิสต์ของ Tuple จัดกลุ่ม Tuple ที่มีค่าตัวที่ 2 (Index 1) เหมือนกัน
Input/Output
Input: [('Python', 'tutorialspoints'), ('Management', 'other'), ('Django', 'tutorialspoints'), ('React', 'tutorialspoints'), ('Social', 'other'), ('Business', 'other')]
Output: {'tutorialspoints': [('Python', 'tutorialspoints'), ('Django', 'tutorialspoints'), ('React', 'tutorialspoints')], 'other': [('Management', 'other'), ('Social', 'other'), ('Business', 'other')]}
วิธีที่ 1: ใช้ Dictionary ธรรมดา
tuples = [('Python', 'tutorialspoints'), ('Management', 'other'), ('Django', 'tutorialspoints'), ('React', 'tutorialspoints'), ('Social', 'other'), ('Business', 'other')]
result = {}
for tup in tuples:
if tup[1] in result:
result[tup[1]].append(tup)
else:
result[tup[1]] = [tup]
print(result)
ผลลัพธ์
{'tutorialspoints': [('Python', 'tutorialspoints'), ('Django', 'tutorialspoints'), ('React', 'tutorialspoints')], 'other': [('Management', 'other'), ('Social', 'other'), ('Business', 'other')]}
วิธีที่ 2: ใช้ collections.defaultdict (แนะนำ)
ไม่ต้องเช็ค key มีอยู่แล้วหรือไม่ defaultdict จะสร้าง list ใหม่อัตโนมัติ
from collections import defaultdict
tuples = [('Python', 'tutorialspoints'), ('Management', 'other'), ('Django', 'tutorialspoints'), ('React', 'tutorialspoints'), ('Social', 'other'), ('Business', 'other')]
result = defaultdict(list)
for tup in tuples:
result[tup[1]].append(tup)
print(dict(result))
ผลลัพธ์
{'tutorialspoints': [('Python', 'tutorialspoints'), ('Django', 'tutorialspoints'), ('React', 'tutorialspoints')], 'other': [('Management', 'other'), ('Social', 'other'), ('Business', 'other')]}
defaultdict ทำให้โค้ดสะอาดขึ้น ลดโอกาสผิดพลาด และเป็น Pythonic มากกว่า