แนวคิด
จากลิสต์ ให้หาช่วง index (start, end) ของแต่ละกลุ่มค่าที่ซ้ำติดกัน ใช้ itertools.groupby และ defaultdict
ตัวอย่างโค้ด
from itertools import groupby
from collections import defaultdict
my_list = [63, 12, 84, 91, 52, 39, 25, 27, 20, 11, 0, 9]
print("ลิสต์:", my_list)
result = defaultdict(list)
current_index = 0
for key, group in groupby(my_list):
group_list = list(group)
count = len(group_list)
result[key].append((current_index, current_index + count - 1))
current_index += count
print("ช่วง Index ของแต่ละค่า:", dict(result))
ผลลัพธ์
ลิสต์: [63, 12, 84, 91, 52, 39, 25, 27, 20, 11, 0, 9]
ช่วง Index ของแต่ละค่า: {63: [(0, 0)], 12: [(1, 1)], 84: [(2, 2)], 91: [(3, 3)], 52: [(4, 4)], 39: [(5, 5)], 25: [(6, 6)], 27: [(7, 7)], 20: [(8, 8)], 11: [(9, 9)], 0: [(10, 10)], 9: [(11, 11)]}
ตัวอย่างที่มีค่าซ้ำติดกัน
my_list = [1, 1, 2, 2, 2, 3, 1, 1]
# ผลลัพธ์:
# 1: [(0, 1), (6, 7)]
# 2: [(2, 4)]
# 3: [(5, 5)]
คำอธิบาย
groupbyจัดกลุ่มค่าติดกันที่เท่ากัน- นับจำนวนในกลุ่ม -> คำนวณ start, end index
defaultdict(list)สะสมช่วงสำหรับค่าเดียวกันที่แยกกลุ่ม (non-consecutive)