Python – 元素的分组连续范围索引
给定元素列表,对于元组列表,其中每个表示每个元素出现的连续性。
Input : test_list = [1, 1, 5, 6, 5, 5]
Output : {1: [(0, 1)], 5: [(2, 2), (4, 5)], 6: [(3, 3)]}
Explanation : 5 present at 2nd idx and also in continuation in 4th and 5th index, and hence recorded range.
Input : test_list = [5, 5, 5, 5, 5, 5]
Output : {5: [(0, 5)]}
Explanation : Only 5 present, hence recorded.
方法:使用 groupby() + defaultdict() + len() + loop
在此,我们使用 groupby() 对连续元素进行分组,defaultdict() 用于初始化元组列表,len() 用于获取重复长度。
Python3
# Python3 code to demonstrate working of
# Grouped Consecutive Range Indices of Elements
# Using groupby() + defaultdict() + len() + loop
from itertools import groupby
from collections import defaultdict
# initializing lists
test_list = [1, 1, 5, 6, 5, 5, 6, 6, 6, 1, 5, 5]
# printing string
print("The original list : " + str(test_list))
idx = 0
res = defaultdict(list)
# grouping Consecutives
for key, sub in groupby(test_list):
ele = len(list(sub))
# append strt index, and till index
res[key].append((idx, idx + ele - 1))
idx += ele
# printing results
print("The grouped dictionary : " + str(dict(res)))
输出
The original list : [1, 1, 5, 6, 5, 5, 6, 6, 6, 1, 5, 5]
The grouped dictionary : {1: [(0, 1), (9, 9)], 5: [(2, 2), (4, 5), (10, 11)], 6: [(3, 3), (6, 8)]}