Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Python – Chỉ số phạm vi liên tiếp nhóm theo giá trị (Grouped Consecutive Range Indices)

Khi cần lấy chỉ số phạm vi (start, end) của các giá trị liên tiếp giống nhau trong list, ta dùng defaultdict, groupby từ itertools.

Ví dụ

from itertools import groupby
from collections import defaultdict

my_list = [63, 12, 84, 91, 52, 39, 25, 27, 20, 11, 0, 9]
print("Danh sách:")
print(my_list)

my_index = 0
my_result = defaultdict(list)

for key, sub in groupby(my_list):
    element = len(list(sub))
    my_result[key].append((my_index, my_index + element - 1))
    my_index += element

print("Dictionary kết quả:")
print(my_result)

Kết quả đầu ra

Danh sách:
[63, 12, 84, 91, 52, 39, 25, 27, 20, 11, 0, 9]
Dictionary kết quả:
defaultdict(, {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)]})

Giải thích

  • groupby(my_list) nhóm các phần tử liên tiếp giống nhau. Với list này, mọi phần tử đều khác nhau nên mỗi nhóm độ dài 1.
  • Với mỗi nhóm: tính độ dài, ghi nhận (start_index, end_index), cập nhật my_index.
  • Kết quả: dictionary ánh xạ giá trị → list các tuple (start, end).

Ví dụ có giá trị lặp: [1,1,1,2,2,3] → {1: [(0,2)], 2: [(3,4)], 3: [(5,5)]}.