Python - 从字符串列表中提取连续相似元素范围的范围
给定一个列表,提取连续相似元素的范围。
Input : test_list = [2, 3, 3, 3, 8, 8]
Output : [(2, 0, 0), (3, 1, 3), (8, 4, 5)]
Explanation : 2 occurs from 0th to 0th index, 3 from 1st to 3rd index.
Input : test_list = [3, 3, 3]
Output : [(3, 0, 3)]
Explanation : 3 from 0th to 3rd index.
方法:使用循环
这是解决这个问题的粗暴方法。在这里,我们循环每个元素并获得相似的元素范围。这些被跟踪并相应地与元素一起附加到列表中。
Python3
# Python3 code to demonstrate working of
# Consecutive Similar elements ranges
# Using loop
# initializing list
test_list = [2, 3, 3, 3, 8, 8, 6, 7, 7]
# printing original list
print("The original list is : " + str(test_list))
res = []
idx = 0
while idx < (len(test_list)):
strt_pos = idx
val = test_list[idx]
# getting last pos.
while (idx < len(test_list) and test_list[idx] == val):
idx += 1
end_pos = idx - 1
# appending in format [ele, strt_pos, end_pos]
res.append((val, strt_pos, end_pos))
# printing result
print("Elements with range : " + str(res))
输出:
The original list is : [2, 3, 3, 3, 8, 8, 6, 7, 7]
Elements with range : [(2, 0, 0), (3, 1, 3), (8, 4, 5), (6, 6, 6), (7, 7, 8)]