【问题标题】:How to count the frequency of the elements in an unordered list?如何计算无序列表中元素的频率?
【发布时间】:2011-01-10 19:55:43
【问题描述】:

我需要在一个无序列表中找到元素的频率

a = [1,1,1,1,2,2,2,2,3,3,4,5,5]

输出->

b = [4,4,2,1,2]

我还想从 a 中删除重复项

a = [1,2,3,4,5]

【问题讨论】:

  • 他们总是像那个例子那样排序吗?
  • @彼得。是的,您已出于发布的目的对列表进行了排序。列表会一直排序吗?
  • 不,列表不会一直排序。这不是家庭作业。
  • 我正在尝试绘制网络的度数分布图。
  • @Peter:请用有用的信息更新您的问题。请不要在您的问题中添加 cmets - 您拥有该问题,您可以修复它以使其完整和清晰。

标签: python counter frequency counting


【解决方案1】:
a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
d = {}
[d.setdefault(el, []).append(1) for el in a]
counts = {k: len(v) for k, v in d.items()}
counts
# {1: 4, 2: 4, 3: 2, 4: 1, 5: 2}

【讨论】:

    【解决方案2】:

    另一种方法是使用字典和list.count,下面是一种幼稚的方法。

    dicio = dict()
    
    a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
    
    b = list()
    
    c = list()
    
    for i in a:
    
       if i in dicio: continue 
    
       else:
    
          dicio[i] = a.count(i)
    
          b.append(a.count(i))
    
          c.append(i)
    
    print (b)
    
    print (c)
    

    【讨论】:

      【解决方案3】:
      a=[1,2,3,4,5,1,2,3]
      b=[0,0,0,0,0,0,0]
      for i in range(0,len(a)):
          b[a[i]]+=1
      

      【讨论】:

        【解决方案4】:
        str1='the cat sat on the hat hat'
        list1=str1.split();
        list2=str1.split();
        
        count=0;
        m=[];
        
        for i in range(len(list1)):
            t=list1.pop(0);
            print t
            for j in range(len(list2)):
                if(t==list2[j]):
                    count=count+1;
                    print count
            m.append(count)
            print m
            count=0;
        #print m
        

        【讨论】:

        • 您回答了一个 非常 古老的问题,还有 13 个其他答案只是代码转储。如果没有某种解释为什么它比其他 13 个答案更好,这不太可能有用。给出答案时,最好给出some explanation as to WHY your answer 是那个。
        猜你喜欢
        • 1970-01-01
        • 2017-02-25
        • 2021-12-04
        • 2021-12-27
        • 1970-01-01
        • 1970-01-01
        • 2019-09-12
        • 2021-08-19
        相关资源
        最近更新 更多