给定一个无序的值列表,比如

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

当前回答

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)

Set集合不允许重复,将一个列表传递给Set()构造函数将给出一个完全唯一对象的可迭代对象。Count()函数在传递列表中的对象时返回一个整数计数。这样,对唯一对象进行计数,每个计数值通过附加到空列表输出来存储 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]

其他回答

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

对于你的第二个问题,只需使用集合操作符。

通过遍历列表并计算它们,手动计算出现的数量,使用collections.defaultdict跟踪到目前为止看到的内容:

from collections import defaultdict

appearances = defaultdict(int)

for curr in a:
    appearances[curr] += 1
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

你可以这样做:

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]

我迟到了,但这也有用,也会帮助到其他人:

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]