編寫一個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

更新於:2021年2月24日

256 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.