如何计算无序列表中元素的频率?[重复]

2024-12-06 08:40:00
admin
原创
127
摘要:问题描述:给定一个无序列表,例如a = [5, 1, 2, 2, 4, 3, 1, 2, 3, 1, 1, 5, 2] 我怎样才能获得列表中出现的每个值的频率,就像这样?# `a` has 4 instances of `1`, 4 of `2`, 2 of `3`, 1 of `4,` 2 of `5` b...

问题描述:

给定一个无序列表,例如

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

我怎样才能获得列表中出现的每个值的频率,就像这样?

# `a` has 4 instances of `1`, 4 of `2`, 2 of `3`, 1 of `4,` 2 of `5`
b = [4, 4, 2, 1, 2] # expected output

解决方案 1:

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

>>> import collections
>>> a = [5, 1, 2, 2, 4, 3, 1, 2, 3, 1, 1, 5, 2]
>>> counter = collections.Counter(a)
>>> counter
Counter({1: 4, 2: 4, 5: 2, 3: 2, 4: 1})
>>> counter.values()
dict_values([2, 4, 4, 1, 2])
>>> counter.keys()
dict_keys([5, 1, 2, 4, 3])
>>> counter.most_common(3)
[(1, 4), (2, 4), (5, 2)]
>>> dict(counter)
{5: 2, 1: 4, 2: 4, 4: 1, 3: 2}
>>> # Get the counts in order matching the original specification,
>>> # by iterating over keys in sorted order
>>> [counter[x] for x in sorted(counter.keys())]
[4, 4, 2, 1, 2]

如果您使用的是 Python 2.6 或更早版本,您可以在此处下载实现。

解决方案 2:

如果列表已排序,则可以使用标准groupbyitertools(如果不是,您可以先对其进行排序,尽管这需要 O(n lg n) 时间):

from itertools import groupby

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

输出:

[4, 4, 2, 1, 2]

解决方案 3:

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]

解决方案 4:

通过遍历列表并计数来手动计算出现次数,并使用collections.defaultdict来跟踪迄今为止已看到的内容:

from collections import defaultdict

appearances = defaultdict(int)

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

解决方案 5:

在 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:

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

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

要删除重复项,请使用集合:

a = list(set(a))

解决方案 7:

您可以这样做:

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]

解决方案 8:

下面是另一个简洁的替代方法,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))}

结果

format: {value: num_of_occurencies}
{1: 4, 2: 4, 3: 2, 4: 1, 5: 2}

解决方案 9:

我会按照以下方式简单地使用 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]

您可以在此处查看文档:http://docs.scipy.org/doc/scipy-0.16.0/reference/generated/scipy.stats.itemfreq.html

解决方案 10:

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

解决方案 11:

假设我们有一个列表:

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}

解决方案 12:

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

解决方案 13:

这个答案更明确

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:

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

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

解决方案 15:

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

解决方案 16:

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

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:

a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
counts = dict.fromkeys(a, 0)
for el in a: counts[el] += 1
print(counts)
# {1: 4, 2: 4, 3: 2, 4: 1, 5: 2}

解决方案 18:

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) 转换为列表,并由同一变量 a 引用

输出

D:MLrecenvScriptspython.exe D:/MLrec/listgroup.py
[4, 4, 2, 1, 2]
[1, 2, 3, 4, 5]

解决方案 19:

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

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

解决方案 20:

#!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
: "
print d
fp1 = open("output.txt","w+")
for k,v in d.items():
fp1.write(str(k)+':'+str(v)+"
")
fp1.close()

解决方案 21:

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]

解决方案 22:

我正在使用 Counter 用一行代码从文本文件单词生成频率字典

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

解决方案 23:

为了记录在案,一个实用的答案是:

>>> 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`accev`

  • 如果e的下一个元素L大于或等于的大小acc,我们必须扩展acc以容纳新的1

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

解决方案 24:

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

import nltk

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

解决方案 25:

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

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

解决方案 26:

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

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

输出为

[4, 4, 2, 1, 2]

解决方案 27:

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

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:

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

解决方案 29:

您可以使用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])

上述代码自动删除列表中的重复项,并打印原始列表和没有重复的列表中每个元素的频率。

一箭双雕!XD

解决方案 30:

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

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)

上/下

[4, 4, 2, 1, 2]
相关推荐
  政府信创国产化的10大政策解读一、信创国产化的背景与意义信创国产化,即信息技术应用创新国产化,是当前中国信息技术领域的一个重要发展方向。其核心在于通过自主研发和创新,实现信息技术应用的自主可控,减少对外部技术的依赖,并规避潜在的技术制裁和风险。随着全球信息技术竞争的加剧,以及某些国家对中国在科技领域的打压,信创国产化显...
工程项目管理   1565  
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   1354  
  信创国产芯片作为信息技术创新的核心领域,对于推动国家自主可控生态建设具有至关重要的意义。在全球科技竞争日益激烈的背景下,实现信息技术的自主可控,摆脱对国外技术的依赖,已成为保障国家信息安全和产业可持续发展的关键。国产芯片作为信创产业的基石,其发展水平直接影响着整个信创生态的构建与完善。通过不断提升国产芯片的技术实力、产...
国产信创系统   21  
  信创生态建设旨在实现信息技术领域的自主创新和安全可控,涵盖了从硬件到软件的全产业链。随着数字化转型的加速,信创生态建设的重要性日益凸显,它不仅关乎国家的信息安全,更是推动产业升级和经济高质量发展的关键力量。然而,在推进信创生态建设的过程中,面临着诸多复杂且严峻的挑战,需要深入剖析并寻找切实可行的解决方案。技术创新难题技...
信创操作系统   27  
  信创产业作为国家信息技术创新发展的重要领域,对于保障国家信息安全、推动产业升级具有关键意义。而国产芯片作为信创产业的核心基石,其研发进展备受关注。在信创国产芯片的研发征程中,面临着诸多复杂且艰巨的难点,这些难点犹如一道道关卡,阻碍着国产芯片的快速发展。然而,科研人员和相关企业并未退缩,积极探索并提出了一系列切实可行的解...
国产化替代产品目录   28  
热门文章
项目管理软件有哪些?
云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用