📌  相关文章
📜  Python - 连续相同的元素计数

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

Python - 连续相同的元素计数

给定元素列表,获取与下一个元素具有相同元素的所有元素。

方法 #1:使用循环 + set()

在此,我们迭代并检查下一个元素,如果等于当前元素,则将其添加到结果列表中,然后将其转换为 set 以获取不同的元素。

Python3
# Python3 code to demonstrate working of 
# Consecutive identical elements count
# Using loop + set()
  
# initializing list
test_list = [4, 5, 5, 5, 5, 6, 6, 7, 8, 2, 2, 10]
  
# printing original list
print("The original list is : " + str(test_list))
  
res = []
for idx in range(0, len(test_list) - 1):
      
    # getting Consecutive elements 
    if test_list[idx] == test_list[idx + 1]:
        res.append(test_list[idx])
          
# getting count of unique elements        
res = len(list(set(res)))
  
# printing result 
print("Consecutive identical elements count : " + str(res))


Python3
# Python3 code to demonstrate working of
# Consecutive identical elements count
# Using list comprehension + set() + len()
  
# initializing list
test_list = [4, 5, 5, 5, 5, 6, 6, 7, 8, 2, 2, 10]
  
# printing original list
print("The original list is : " + str(test_list))
  
# getting Consecutive elements
res = [test_list[idx] for idx in range(
    0, len(test_list) - 1) if test_list[idx] == test_list[idx + 1]]
  
# getting count of unique elements
res = len(list(set(res)))
  
# printing result
print("Consecutive identical elements count : " + str(res))


输出
The original list is : [4, 5, 5, 5, 5, 6, 6, 7, 8, 2, 2, 10]
Consecutive identical elements count : 3

方法 #2:使用列表推导 + set() + len()

这种方法与上面的方法类似,不同之处在于它解决这个问题的方法更短。 len() 和 set() 用于获取唯一元素计数的任务。

蟒蛇3

# Python3 code to demonstrate working of
# Consecutive identical elements count
# Using list comprehension + set() + len()
  
# initializing list
test_list = [4, 5, 5, 5, 5, 6, 6, 7, 8, 2, 2, 10]
  
# printing original list
print("The original list is : " + str(test_list))
  
# getting Consecutive elements
res = [test_list[idx] for idx in range(
    0, len(test_list) - 1) if test_list[idx] == test_list[idx + 1]]
  
# getting count of unique elements
res = len(list(set(res)))
  
# printing result
print("Consecutive identical elements count : " + str(res))
输出
The original list is : [4, 5, 5, 5, 5, 6, 6, 7, 8, 2, 2, 10]
Consecutive identical elements count : 3