数组中数字的频率

时间:2019-09-04 01:30:15

标签: python frequency-distribution

我想获取未排序数组中数字的频率。我正在获取数字的频率,但是输出多次显示特定数字的频率。我希望结果频率仅显示一次。

A = [2,5,1,2,4,6,3,10,3,4,3,2,3,2,15]
B = max(A) + 1
F =[None] * B
for i in range(0,B):
    F[i] = 0 
for j in range(0,len(A)):
    F[A[j]] = F[A[j]] + 1
for k in range(0,len(A)):
    if F[A[k]] != 0:
        print("Frequency of ", A[k] , " is : " , F[A[k]])

获得的输出显示出说2次的频率,四次。

Frequency of  2  is :  4
Frequency of  5  is :  1
Frequency of  1  is :  1
Frequency of  2  is :  4
Frequency of  4  is :  2
Frequency of  6  is :  1
Frequency of  3  is :  4
Frequency of  10  is :  1
Frequency of  3  is :  4
Frequency of  4  is :  2
Frequency of  3  is :  4
Frequency of  2  is :  4
Frequency of  3  is :  4
Frequency of  2  is :  4
Frequency of  15  is :  1

3 个答案:

答案 0 :(得分:2)

为此使用collections.Counter

In [1]: from collections import Counter

In [2]: A = [2,5,1,2,4,6,3,10,3,4,3,2,3,2,15]

In [3]: for k, v in Counter(A).items():
   ...:     print('Frequency of {} is {}'.format(k, v))
   ...:
Frequency of 2 is 4
Frequency of 5 is 1 ...

答案 1 :(得分:0)

您可以为此使用dict数据结构。在以下位置查看注释良好的代码:

# This function creates the collection frequencies
def get_collection_frequency(mylist):
    # Dictionary data structure is used
    mydict = {}
    # Loop through the input list
    for index in mylist:
        # If the item is already there
        if (index in mydict): 
            # Increase its frequency
            mydict[index] += 1
        # If it is not
        else: 
            # Set its frequency equal to 1
            mydict[index] = 1

    # Return the dictionary
    return mydict

A = [2,5,1,2,4,6,3,10,3,4,3,2,3,2,15]

new = get_collection_frequency(A)
print(new)

返回:{2: 4, 5: 1, 1: 1, 4: 2, 6: 1, 3: 4, 10: 1, 15: 1}

答案 2 :(得分:0)

获取列表集以删除多个匹配项,然后循环遍历:

for num in set(A):
    print("Frequency of {} is {}".format(num,A.count(num)))

输出:

Frequency of 1 is 1
Frequency of 2 is 4
Frequency of 3 is 4
Frequency of 4 is 2
Frequency of 5 is 1
Frequency of 6 is 1
Frequency of 10 is 1
Frequency of 15 is 1