ในบทช่วยสอนนี้ เราจะเขียนโปรแกรมที่จัดกลุ่มทูเพิลทั้งหมดจากรายการที่มีองค์ประกอบเดียวกันกับองค์ประกอบที่สอง มาดูตัวอย่างให้เข้าใจกันชัดๆ
อินพุต
[('Python', 'tutorialspoints'), ('Management', 'other'), ('Django', 'tutorialspoints'), ('React',
'tutorialspoints'), ('Social', 'other'), ('Business', 'other')] ผลลัพธ์
{'tutorialspoint': [('Python', 'tutorialspoints'), ('Django', 'tutorialspoints'), ('React', 'tutorialspoints')],
'other’: [('Management', 'other'), ('Social', 'other'), ('Business', 'other')]} เราต้องจัดกลุ่มทูเพิลจากรายการ มาดูขั้นตอนการแก้ปัญหากัน
- เริ่มต้นรายการด้วยทูเพิลที่จำเป็น
- สร้างพจนานุกรมเปล่า
- วนซ้ำรายการของทูเพิล
- ตรวจสอบว่าองค์ประกอบที่สองของ tuple มีอยู่ในพจนานุกรมอยู่แล้วหรือไม่
- หากมีอยู่แล้ว ให้ผนวก tuple ปัจจุบันต่อท้ายรายการ
- อย่างอื่นเริ่มต้นคีย์ด้วยรายการที่มีทูเพิลปัจจุบัน
- ในตอนท้าย คุณจะได้พจนานุกรมที่มีการแก้ไขที่จำเป็น
ตัวอย่าง
# initializing the list with tuples
tuples = [('Python', 'tutorialspoints'), ('Management', 'other'), ('Django', 't
ialspoints'), ('React', 'tutorialspoints'), ('Social', 'other'), ('Business', 'othe
r')]
# empty dict
result = {}
# iterating over the list of tuples
for tup in tuples:
# checking the tuple element in the dict
if tup[1] in result:
# add the current tuple to dict
result[tup[1]].append(tup)
else:
# initiate the key with list
result[tup[1]] = [tup]
# priting the result
print(result) ผลลัพธ์
หากคุณเรียกใช้โค้ดด้านบน คุณจะได้ผลลัพธ์ดังต่อไปนี้
{'tutorialspoints': [('Python', 'tutorialspoints'), ('Django', 'tutorialspoints
('React', 'tutorialspoints')], 'other': [('Management', 'other'), ('Social', 'other
'), ('Business', 'other')]} เราข้าม ถ้า เงื่อนไขในโปรแกรมข้างต้นโดยใช้ defaultdict . มาแก้ปัญหาโดยใช้ defaultdict .
ตัวอย่าง
# importing defaultdict from collections
from collections import defaultdict
# initializing the list with tuples
tuples = [('Python', 'tutorialspoints'), ('Management', 'other'), ('Django', 't
ialspoints'), ('React', 'tutorialspoints'), ('Social', 'other'), ('Business', 'othe
r')]
# empty dict with defaultdict
result = defaultdict(list)
# iterating over the list of tuples
for tup in tuples:
result[tup[1]].append(tup)
# priting the result
print(dict(result)) ผลลัพธ์
หากคุณเรียกใช้โค้ดด้านบน คุณจะได้ผลลัพธ์ดังต่อไปนี้
{'tutorialspoints': [('Python', 'tutorialspoints'), ('Django', 'tutorialspoints
('React', 'tutorialspoints')], 'other': [('Management', 'other'), ('Social', 'other
'), ('Business', 'other')]} บทสรุป
คุณสามารถแก้ปัญหาได้ด้วยวิธีต่างๆ ตามที่คุณต้องการ เราได้เห็นสองวิธีที่นี่ หากคุณมีข้อสงสัยใดๆ ในบทแนะนำ โปรดระบุในส่วนความคิดเห็น