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

问题描述 投票:234回答:30

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

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]

我需要找到无序列表中元素的频率a = [1,1,1,1,2,2,2,2,3,3,3,4,5,5]输出-> b = [4 ,4,2,1,2]我也想从aa = [1,2,3,4,5]

python counter frequency counting
30个回答
143
投票

由于已订购列表,您可以执行以下操作:


529
投票

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


107
投票

Python 2.7+引入了字典理解。从列表中构建字典将使您获得计数并消除重复项。


48
投票

计算出场次数:


26
投票

在Python 2.7+中,您可以使用a = set(a) 来计数项目


25
投票

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


20
投票

这里是另一个使用a = list(set(a)) 的简洁表述,它也适用于无序输入:


15
投票

您可以这样做:


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

7
投票

我将以以下方式简单地使用scipy.stats.itemfreq:



4
投票

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


3
投票

此答案更为明确


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}

3
投票

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


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

2
投票

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


1
投票
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]))

1
投票
#!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()

1
投票
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)

1
投票

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


1
投票

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


0
投票

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


0
投票

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


0
投票

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


0
投票

作为记录,一个实用的答案:


0
投票

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


-1
投票

另一种方法是在天真的方法下面使用字典和list.count。


-1
投票
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
© www.soinside.com 2019 - 2024. All rights reserved.