Python – 提取 Range 连续出现的元素
有时在处理数据时,我们可能会遇到一个问题,即我们需要选择一些范围时间连续出现的元素。此问题可能发生在许多域中。让我们讨论一些可以解决这个问题的方法。
方法 #1:使用groupby()
+ 列表理解
可以使用上述功能执行此任务。在此,我们将所有连续出现的数字分组。我们使用列表推导来迭代列表。
# Python3 code to demonstrate working of
# Extract elements with Range consecutive occurrences
# using groupby() + list comprehension
from itertools import groupby
# initialize list
test_list = [1, 1, 4, 5, 5, 6, 7, 7, 7, 8, 8, 8, 8]
# printing original list
print("The original list : " + str(test_list))
# initialize strt, end
strt, end = 2, 3
# Extract elements with Range consecutive occurrences
# using groupby() + list comprehension
res1 = [i for i, j in groupby(test_list) if len(list(j)) <= end]
res2 = [i for i, j in groupby(test_list) if len(list(j)) >= strt]
res = list(set(res1) & set(res2))
# printing result
print("The range consecutive elements are : " + str(res))
输出 :
The original list : [1, 1, 4, 5, 5, 6, 7, 7, 7, 8, 8, 8, 8]
The range consecutive elements are : [1, 5, 7]
方法 #2:使用列表理解 + slice() + groupby()
也可以使用上述功能执行此任务。在这里,我们只是以与上面类似的方式进行分组,但我们提取连续元素的方式是通过slice()
。
# Python3 code to demonstrate working of
# Extract elements with Range consecutive occurrences
# using groupby() + list comprehension + islice()
from itertools import groupby, islice
# initialize list
test_list = [1, 1, 4, 5, 5, 6, 7, 7, 7, 8, 8, 8]
# printing original list
print("The original list : " + str(test_list))
# initialize strt, end
strt, end = 2, 3
# Extract elements with Range consecutive occurrences
# using groupby() + list comprehension + islice()
res1 = [i for i, j in groupby(test_list) if len(list(islice(j, 0, strt))) >= strt]
res2 = [i for i, j in groupby(test_list) if len(list(islice(j, 0, end))) <= end]
res = list(set(res1) & set(res2))
# printing result
print("The range consecutive elements are : " + str(res))
输出 :
The original list : [1, 1, 4, 5, 5, 6, 7, 7, 7, 8, 8, 8]
The range consecutive elements are : [1, 5, 7, 8]