Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何计算无序列表中元素的频率?_Python_Counter_Frequency_Counting - Fatal编程技术网

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

Python 如何计算无序列表中元素的频率?,python,counter,frequency,counting,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] 对于第一个问题,迭代列表并使用字典跟踪元素的存在 对于第二个问题,只需使用set运算符。计算出现次数: from collections import defaultdict appearances = defaultdict(int) for curr in a: appearanc

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

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]

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


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

计算出现次数:

from collections import defaultdict

appearances = defaultdict(int)

for curr in a:
    appearances[curr] += 1
要删除重复项,请执行以下操作:

a = set(a) 

计算元素的频率可能最好使用字典:

b = {}
for item in a:
    b[item] = b.get(item, 0) + 1
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)
要删除重复项,请使用集合:

a = list(set(a))

注意:在使用
groupby

如果列表是有序列表,则可以使用
itertools
包中的
groupby

a=[1,1,1,2,2,2,3,3,4,5,5]
从itertools导入groupby
[len(列表(组))用于键,groupby(a)中的组]
输出:

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

更新:注意排序需要O(n log(n))时间。

在Python2.7+中,您可以使用

>>> 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]
在Python 2.7(或更新版本)中,您可以使用:


如果您使用的是Python2.6或更早版本,您可以下载它。

Python2.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]

这个答案更加明确

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}

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

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

我将以以下方式简单地使用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]
您可以在此处查看文档:

您可以这样做:

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

[4, 4, 2, 1, 2]
(array([1, 2, 3, 4, 5]), array([4, 4, 2, 1, 2], dtype=int64))
[4, 4, 2, 1, 2]
第一个数组是值,第二个数组是具有这些值的元素数

因此,如果您只想获得包含数字的数组,则应使用以下命令:

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

您可以使用python中提供的内置函数

l.count(l[i])


  d=[]
  for i in range(len(l)):
        if l[i] not in d:
             d.append(l[i])
             print(l.count(l[i])
上面的代码自动删除列表中的重复项,并打印原始列表和无重复项列表中每个元素的频率

>>> 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]

一枪两鸟!xd

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

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

要删除重复项并保持顺序,请执行以下操作:

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

我用计数器从一行代码中的文本文件单词生成一个freq.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])

我已经很晚了,但这也会起作用,并且会帮助其他人:

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]

作为记录,功能性回答:

>>> 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]
L=[1,1,1,2,2,2,2,3,4,5,5] >>>导入功能工具
>>>>>>functools.reduce(lambda acc,e:[v+(i==e)表示枚举中的i,v(acc,1)],如果e这里有另一个使用
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}
  • Set集合不允许重复,将列表传递给Set()构造函数将提供一个完全唯一对象的iterable。传递列表中的对象时,count()函数将返回一个整数计数。这样,将对唯一对象进行计数,并通过将每个计数值附加到空列表输出来存储
  • list()构造函数用于将集合(a)转换为list,并由同一变量a引用
  • 输出

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

    使用字典的简单解决方案

    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]))
    

    另一种方法是使用更重但功能强大的库NLTK

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

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

    #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)
    

    要在列表中查找唯一的元素,请执行以下操作:

    a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
    a = list(set(a))
    
    要使用字典查找排序数组中唯一元素的计数,请执行以下操作:

    b = {}
    for item in a:
        b[item] = b.get(item, 0) + 1
    
    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)
    
    参考:


    对于无序列表,您应该使用:

    [a.count(el) for el in set(a)]
    
    输出是

    [4, 4, 2, 1, 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}
    

    他们总是像那个例子中那样排序吗?@Peter。是的,你对列表进行排序是为了发帖。列表总是会排序吗?不,列表不会总是排序。这不是家庭作业。我正在试图绘制网络的度分布图。@Peter:请用有用的信息更新你的问题。请不要给你的问题添加注释——你拥有这个问题,你可以把它修改得完整而清晰。你能用
    groupby
    详细解释一下第一个答案吗?我想知道它的效率与dict方法相比如何,虽然python groupby在看到值发生变化时会创建新的组。在这种情况下,1,1,2,1,1,1,1]会返回[3,1,3]。如果您希望得到[6,1],那么请确保在使用groupby之前对数据进行排序。@CristianCiupitu:
    sum(1代表uuu.in group)
    。这不是一个解决方案。输出不会说明计算了什么。
    [(key,len(list(group))(key,groupby(a)中的group)]
    {key:len(list(group)(group))代表key,groupby(a)中的group}
    @buhtzusing lists
    count
    贵得离谱,在这种情况下是不必要的。@IdanK为什么count贵?@KritikaRajain对于列表中的每个唯一元素,您迭代整个列表以生成一个计数(列表中唯一元素数的平方)。相反,您可以在列表上迭代一次,并计算每个唯一元素的数量(列表大小为线性)。如果列表只有一个唯一元素,则结果将是相同的。此外,此方法需要额外的中间集。collections.defaultdict为+1。此外,在python 3.x中,查找collections.Counter。它与collections.defaultdict(int)相同@hughdbrown,实际上,
    计数器
    可以使用多种数字类型,包括
    浮点
    十进制
    ,而不仅仅是
    int
    @phkahler:我的只会比这稍微好一点。如果这可以通过一点小小的改变来改进,我就不值得单独发布一个答案了。这样做的目的是为了得到最好的答案呃,我可以简单地编辑这个,但我更愿意让原作者有机会自己进行改进。@S.Lott代码更干净,无需导入[4, 4, 2, 1, 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}