📜  Python - 相似的连续元素频率

📅  最后修改于: 2022-05-13 01:54:27.127000             🧑  作者: Mango

Python - 相似的连续元素频率

有时,在使用Python时,我们可能会遇到一个问题,即我们必须找到连续出现的元素。这个问题在学校编程和数据工程中很有用。让我们讨论可以执行此任务的某些方式。

方法#1:使用循环
这是可以解决此问题的蛮力方法。在此,我们迭代循环并计数,直到我们得到其他数字。

# Python3 code to demonstrate 
# Similar Consecutive elements frequency
# using loop
  
# initializing list 
test_list = [2, 2, 3, 3, 3, 3, 4, 4, 4]
  
# printing original list
print ("The original list is : " + str(test_list))
  
# Similar Consecutive elements frequency
# using loop
res = []
count = 1
for ele in range(0, len(test_list) -1):
    if test_list[ele] != test_list[ele + 1]:
        res.append((test_list[ele], count))
        count = 1
    else :
        count = count + 1
res.append((test_list[len(test_list) -1], count))
  
# printing result 
print ("The consecutive element frequency is : " + str(res))
输出 :
The original list is : [2, 2, 3, 3, 3, 3, 4, 4, 4]
The consecutive element frequency is : [(2, 2), (3, 4), (4, 3)]

方法 #2:使用groupby() + len() + 列表理解
上述方法的组合可用于执行此任务。在此,我们将连续元素分组并使用 len() 提取计数。列表推导用于将两个逻辑绑定在一起。

# Python3 code to demonstrate 
# Similar Consecutive elements frequency
# using groupby() + len() + list comprehension
from itertools import groupby
  
# initializing list 
test_list = [2, 2, 3, 3, 3, 3, 4, 4, 4]
  
# printing original list
print ("The original list is : " + str(test_list))
  
# Similar Consecutive elements frequency
# using groupby() + len() + list comprehension
res = [(k, len(list(j))) for k, j in groupby(test_list)]
  
# printing result 
print ("The consecutive element frequency is : " + str(res))
输出 :
The original list is : [2, 2, 3, 3, 3, 3, 4, 4, 4]
The consecutive element frequency is : [(2, 2), (3, 4), (4, 3)]