如何计算列表中元素的频率?

时间:2010-01-29 12:08:21

标签: python counter frequency counting

我需要找到列表中元素的频率

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

输出 - >

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

此外,我想从

中删除重复项
a = [1,2,3,4,5]

33 个答案:

答案 0 :(得分:447)

在Python 2.7(或更新版本)中,您可以使用collections.Counter

import collections
a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
counter=collections.Counter(a)
print(counter)
# Counter({1: 4, 2: 4, 3: 2, 5: 2, 4: 1})
print(counter.values())
# [4, 4, 2, 1, 2]
print(counter.keys())
# [1, 2, 3, 4, 5]
print(counter.most_common(3))
# [(1, 4), (2, 4), (3, 2)]

如果您使用的是Python 2.6或更早版本,则可以下载here

答案 1 :(得分:116)

由于订购了清单,您可以这样做:

a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
from itertools import groupby
[len(list(group)) for key, group in groupby(a)]

输出:

[4, 4, 2, 1, 2]

答案 2 :(得分:94)

Python 2.7+引入了词典理解。从列表中构建字典将为您提供计数以及删除重复项。

>>> a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
>>> d = {x:a.count(x) for x in a}
>>> d
{1: 4, 2: 4, 3: 2, 4: 1, 5: 2}
>>> a, b = d.keys(), d.values()
>>> a
[1, 2, 3, 4, 5]
>>> b
[4, 4, 2, 1, 2]

答案 3 :(得分:45)

计算出场次数:

from collections import defaultdict

appearances = defaultdict(int)

for curr in a:
    appearances[curr] += 1

删除重复项:

a = set(a) 

答案 4 :(得分:23)

计算元素的频率可能最好用字典来完成:

b = {}
for item in a:
    b[item] = b.get(item, 0) + 1

要删除重复项,请使用set:

a = list(set(a))

答案 5 :(得分:20)

在Python 2.7+中,您可以使用collections.Counter来计算项目

>>> a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
>>>
>>> from collections import Counter
>>> c=Counter(a)
>>>
>>> c.values()
[4, 4, 2, 1, 2]
>>>
>>> c.keys()
[1, 2, 3, 4, 5]

答案 6 :(得分:9)

你可以这样做:

import numpy as np
a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
np.unique(a, return_counts=True)

输出:

(array([1, 2, 3, 4, 5]), array([4, 4, 2, 1, 2], dtype=int64))

第一个数组是值,第二个数组是具有这些值的元素数。

所以如果你想获得数字的数组,你应该使用它:

np.unique(a, return_counts=True)[1]

答案 7 :(得分:7)

seta = set(a)
b = [a.count(el) for el in seta]
a = list(seta) #Only if you really want it.

答案 8 :(得分:6)

from collections import Counter
a=["E","D","C","G","B","A","B","F","D","D","C","A","G","A","C","B","F","C","B"]

counter=Counter(a)

kk=[list(counter.keys()),list(counter.values())]

pd.DataFrame(np.array(kk).T, columns=['Letter','Count'])

答案 9 :(得分:6)

这是使用itertools.groupby的另一个简洁选择,它也适用于无序输入:

from itertools import groupby

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

results = {value: len(list(freq)) for value, freq in groupby(sorted(items))}

结果

{1: 4, 2: 4, 3: 2, 4: 1, 5: 2}

答案 10 :(得分:5)

我只是按照以下方式使用scipy.stats.itemfreq:

from scipy.stats import itemfreq

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

freq = itemfreq(a)

a = freq[:,0]
b = freq[:,1]

您可以在此处查看文档:{​​{3}}

答案 11 :(得分:4)

def frequencyDistribution(data):
    return {i: data.count(i) for i in data}   

print frequencyDistribution([1,2,3,4])

...

 {1: 1, 2: 1, 3: 1, 4: 1}   # originalNumber: count

答案 12 :(得分:3)

对于您的第一个问题,迭代列表并使用字典来跟踪元素存在。

关于第二个问题,只需使用set运算符。

答案 13 :(得分:3)

这个答案更明确

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

d = {}
for item in a:
    if item in d:
        d[item] = d.get(item)+1
    else:
        d[item] = 1

for k,v in d.items():
    print(str(k)+':'+str(v))

# output
#1:4
#2:4
#3:3
#4:2

#remove dups
d = set(a)
print(d)
#{1, 2, 3, 4}

答案 14 :(得分:2)

要在列表中查找唯一元素:

a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
a = list(set(a))

要使用字典查找排序数组中唯一元素的数量:

def CountFrequency(my_list): 
# Creating an empty dictionary  
freq = {} 
for item in my_list: 
    if (item in freq): 
        freq[item] += 1
    else: 
        freq[item] = 1

for key, value in freq.items(): 
    print ("% d : % d"%(key, value))

# Driver function 
if __name__ == "__main__":  
my_list =[1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2] 

CountFrequency(my_list)

参考:

GeeksforGeeks

答案 15 :(得分:2)

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

# 1. Get counts and store in another list
output = []
for i in set(a):
    output.append(a.count(i))
print(output)

# 2. Remove duplicates using set constructor
a = list(set(a))
print(a)
  1. Set集合不允许重复,将列表传递给set()构造函数将提供完全唯一的对象的可迭代项。传递列表中的对象时,count()函数返回整数计数。这样,对唯一对象进行计数,并通过将其附加到一个空列表输出中来存储每个计数值
  2. list()构造函数用于将set(a)转换为list并由相同的变量a引用

输出

D:\MLrec\venv\Scripts\python.exe D:/MLrec/listgroup.py
[4, 4, 2, 1, 2]
[1, 2, 3, 4, 5]

答案 16 :(得分:2)

我来晚了,但这也可以工作,并且可以帮助其他人:

a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
freq_list = []
a_l = list(set(a))

for x in a_l:
    freq_list.append(a.count(x))


print 'Freq',freq_list
print 'number',a_l

会产生这个。

Freq  [4, 4, 2, 1, 2]
number[1, 2, 3, 4, 5]

答案 17 :(得分:2)

数据。假设我们有一个列表:

fruits = ['banana', 'banana', 'apple', 'banana']

解决方案。然后,通过执行以下操作,我们可以找出列表中每个水果的数量:

import numpy as np    
(unique, counts) = np.unique(fruits, return_counts=True)
{x:y for x,y in zip(unique, counts)}

输出

{'banana': 3, 'apple': 1}

答案 18 :(得分:1)

from collections import OrderedDict
a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
def get_count(lists):
    dictionary = OrderedDict()
    for val in lists:
        dictionary.setdefault(val,[]).append(1)
    return [sum(val) for val in dictionary.values()]
print(get_count(a))
>>>[4, 4, 2, 1, 2]

删除重复项并维护订单:

list(dict.fromkeys(get_count(a)))
>>>[4, 2, 1]

答案 19 :(得分:1)

我正在使用Counter来生成频率。来自1行代码中的文本文件单词的dict

def _fileIndex(fh):
''' create a dict using Counter of a
flat list of words (re.findall(re.compile(r"[a-zA-Z]+"), lines)) in (lines in file->for lines in fh)
'''
return Counter(
    [wrd.lower() for wrdList in
     [words for words in
      [re.findall(re.compile(r'[a-zA-Z]+'), lines) for lines in fh]]
     for wrd in wrdList])

答案 20 :(得分:0)

如果您不想使用任何库并保持简单和简短,可以尝试这种方法!

a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
marked = []
b = [(a.count(i), marked.append(i))[0] for i in a if i not in marked]
print(b)

O / P

[4, 4, 2, 1, 2]

答案 21 :(得分:0)

您可以使用python

中提供的内置函数
SQLiteDatabase.java

上面的代码会自动删除列表中的重复项,并且还会打印原始列表中每个元素的频率以及没有重复项的列表。

一杆两只鸟! X D

答案 22 :(得分:0)

num=[3,2,3,5,5,3,7,6,4,6,7,2]
print ('\nelements are:\t',num)
count_dict={}
for elements in num:
    count_dict[elements]=num.count(elements)
print ('\nfrequency:\t',count_dict)

答案 23 :(得分:0)

记录下来,一个功能性答案:

>>> L = [1,1,1,1,2,2,2,2,3,3,4,5,5]
>>> import functools
>>> >>> functools.reduce(lambda acc, e: [v+(i==e) for i, v in enumerate(acc,1)] if e<=len(acc) else acc+[0 for _ in range(e-len(acc)-1)]+[1], L, [])
[4, 4, 2, 1, 2]

如果您也算零,那会更干净:

>>> functools.reduce(lambda acc, e: [v+(i==e) for i, v in enumerate(acc)] if e<len(acc) else acc+[0 for _ in range(e-len(acc))]+[1], L, [])
[0, 4, 4, 2, 1, 2]

说明:

  • 我们从一个空的acc列表开始;
  • 如果e的下一个元素L小于acc的大小,我们只更新此元素:v+(i==e)表示v+1,如果索引i中的acc是当前元素e,否则是先前的值v;
  • 如果e的下一个元素L大于或等于acc的大小,我们必须扩展acc来容纳新的1

不必对元素进行排序(itertools.groupby)。如果数字为负,则会得到奇怪的结果。

答案 24 :(得分:0)

使用字典的简单解决方案。

def frequency(l):
     d = {}
     for i in l:
        if i in d.keys():
           d[i] += 1
        else:
           d[i] = 1

     for k, v in d.iteritems():
        if v ==max (d.values()):
           return k,d.keys()

print(frequency([10,10,10,10,20,20,20,20,40,40,50,50,30]))

答案 25 :(得分:0)

执行此操作的另一种方法,尽管使用了功能更强大的NLTK库。

import nltk

fdist = nltk.FreqDist(a)
fdist.values()
fdist.most_common()

答案 26 :(得分:0)

找到了另一种使用集合的方法。

#ar is the list of elements
#convert ar to set to get unique elements
sock_set = set(ar)

#create dictionary of frequency of socks
sock_dict = {}

for sock in sock_set:
    sock_dict[sock] = ar.count(sock)

答案 27 :(得分:0)

使用另一种不使用集合的算法的另一种解决方案:

def countFreq(A):
   n=len(A)
   count=[0]*n                     # Create a new list initialized with '0'
   for i in range(n):
      count[A[i]]+= 1              # increase occurrence for value A[i]
   return [x for x in count if x]  # return non-zero count

答案 28 :(得分:0)

#!usr/bin/python
def frq(words):
    freq = {}
    for w in words:
            if w in freq:
                    freq[w] = freq.get(w)+1
            else:
                    freq[w] =1
    return freq

fp = open("poem","r")
list = fp.read()
fp.close()
input = list.split()
print input
d = frq(input)
print "frequency of input\n: "
print d
fp1 = open("output.txt","w+")
for k,v in d.items():
fp1.write(str(k)+':'+str(v)+"\n")
fp1.close()

答案 29 :(得分:-1)

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

答案 30 :(得分:-1)

对于无序列表,应使用:

[a.count(el) for el in set(a)]

输出为

[4, 4, 2, 1, 2]

答案 31 :(得分:-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)

答案 32 :(得分:-3)

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