【问题标题】:Code in Python that count repeated elements and return the item repeated most times and how many timesPython中的代码计算重复元素并返回重复次数最多的项目以及重复次数
【发布时间】:2020-01-03 20:37:13
【问题描述】:

我有一个整数列表,我需要找出哪个项目重复次数最多,然后函数应该返回两个变量(值,数字)值是重复的元素,数字是重复的次数

输入

B = [1, 5, 1, 3, 5, 1]

输出

1 3

我得到了一个适用于列表中第一项的代码,但是当它进入下一个循环时,它从零开始,所以我很难存储我在第一个循环中得到的内容并与第二个循环进行比较看看我需要保留哪一个。

对于这个功能,我不允许使用任何模块或库,如“count”或任何其他高级代码,就像新手级别一样简单

def counting(B):
   n = len(B)
   tempcount = []
   tempcval = []

   for i in range(0,n-1):
      cval=B[i]
      count = 0

      for next in B:
         if next == cval:
              count += 1

         tempcount.append(count)
         tempcval.append(cval)

      return count,cval

def main():
   list = [1, 5, 1, 3, 5, 1]
   a,b = counting(list)
   print(a,b)

main()

预期输出

3 1

实际输出

2 5

【问题讨论】:

  • 字典应该是最直接的答案,使用列表中的项目作为键和值作为计数。唯一需要注意的是记住在访问任何值之前用“in”测试密钥的存在
  • 注意:您的 return 语句在 for 循环内,这可能不是您想要的。

标签: python-3.x list for-loop pycharm counting


【解决方案1】:

一个好的解决方案可能是使用collections.Counter:

>>> import collections
>>> c = collections.Counter([1, 5, 1, 3, 5, 1])
>>> c
Counter({1: 3, 5: 2, 3: 1})
>>> c.most_common(1)
[(1, 3)]

在函数中可能如下所示:

import collections

def counting(the_list):
    c = collections.Counter(the_list)
    data = c.most_common(1)[0]
    print('value', data[0])
    print('count', data[1])

    return data[1], data[0]

【讨论】:

    【解决方案2】:

    由于我熟悉 pandas,dataframe 操作库

    如果我是你,我会使用

    import pandas as pd
    temp = pd.Series([1, 5, 1, 3, 5, 1])
    temp2 = temp.value_counts()
    temp2.index[0], temp2.iloc[0]
    

    但第一个答案似乎更简单哈哈哈

    【讨论】:

      【解决方案3】:

      一种不需要任何导入的解决方案。您的代码存在一些问题,因为您实际上从未使用过这些 tempcount 和 tempcval。你会附加到它们,但没有别的。这次我带他们去兜风,并使用它们来存储每个值的计数,基本上将 tempcval 变成了输入列表的非重复列表。

      def counting(B):
         n = len(B)
         tempcount = []
         tempcval = []
      
         for next in B:
            if next in tempcval:
               point = tempcval.index(next)
               tempcount[point] = tempcount[point] + 1
            else:
               tempcval.append(next)
               tempcount.append(1)
      
         maxCount = max(tempcount)
         point = tempcount.index(maxCount)
      
         return tempcount[point],tempcval[point]
      
      def main():
         list = [1, 5, 1, 3, 5, 1]
         a,b = counting(list)
         print(a,b)
      
      main()
      

      因此,此代码存在一个问题。它在给定的示例中有效,但假设你给了

      list = [1, 5, 1, 3, 5, 1, 5]
      

      代码仍会返回 3 1,因为 1 出现在 5 之前。

      【讨论】:

        猜你喜欢
        • 2019-04-21
        • 1970-01-01
        • 2016-04-21
        • 2012-06-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多