编写一个Python程序来查找序列中重复次数最多的元素
假设您有以下序列:
Series is: 0 1 1 22 2 3 3 4 4 22 5 5 6 22
重复次数最多的元素的结果是:
Repeated element is: 22
解决方案
为了解决这个问题,我们将遵循以下方法:
定义一个序列
初始计数设置为0,max_count值设置为序列的第一个元素值data[0]
count = 0 max_count = data[0]
创建for循环来访问序列数据,并将frequency_count设置为l.count(i)
for i in data: frequency_count = l.count(i)
设置if条件与max_count值进行比较,如果条件为真,则将计数赋值给frequency_count并将max_count更改为序列中当前的元素。最后,打印max_count。定义如下:
if(frequency_count > max_count):
count = frequency_count
max_count = i
print("Repeated element is:", max_count)示例
让我们看看下面的实现来更好地理解:
import pandas as pd
l = [1,22,3,4,22,5,22]
data = pd.Series(l)
print("Series is:\n", data)
count = 0
max_count = data[0]
for i in data:
frequency_count = l.count(i)
if(frequency_count > max_count):
count = frequency_count
max_count = i
print("Repeated element is:", max_count)输出
Series is: 0 1 1 22 2 3 3 4 4 22 5 5 6 22 dtype: int64 Repeated element is: 22
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP