简体   繁体   中英

Can I write codes to count the frequency of each integer, and then print each integer with its frequency?

Given a list of integers: Write codes to count the frequency of each integer, and then print each integer with its frequency. (The order of the elements does not matter) For example, for n = [1,1,1,3,3,3,2,2,4,4,4,4,4,5,5,5,6,6,6,6,6,6,6,6,6] , the print out will be:

1 3
2 2
3 3
4 5
5 3
6 9

And make each two numbers in a row. ie in the first row, 3 is the frequency of 1 in the list n

My code is like that, and it shows 'builtin_function_or_method' object is not subscriptable:

n = [1,1,1,3,3,3,2,2,4,4,4,4,4,5,5,5,6,6,6,6,6,6,6,6,6]

def question_7_1(n=n):
    count=0
    for i in n:
        if i==n.index[i]:
            count=count+1
            print(i,count)

Implementing it in a comparatively easy to understand method.

n = [1,1,1,3,3,3,2,2,4,4,4,4,4,5,5,5,6,6,6,6,6,6,6,6,6]

freq = {}
for i in n: 
    if i in freq: 
      freq[i] += 1
    else: 
      freq[i] = 1

print ("Count is :\n "+  str(freq)) 

This should return the integer and the count.

The error in your code is the use of n.index[i] . It should've been n.index(i) .

Output:

Count is :
 {1: 3, 3: 3, 2: 2, 4: 5, 5: 3, 6: 9}

For a better implementation, refer to the answer by @Sheri!

n = [1,1,1,3,3,3,2,2,4,4,4,4,4,5,5,5,6,6,6,6,6,6,6,6,6]

def question_7_1(n):
    dict ={}
    for j in n:
        count=1
        #print(j)
        if j in dict.keys():
            count = dict[j]
            count=count+1
            dict[j] = count
        else:
            dict[j] = count
    dict[j] = count
    #print(dict)
    return dict

result = question_7_1(n)
print(result)

output :

{1: 3, 2: 2, 3: 3, 4: 5, 5: 3, 6: 9} 

Tons of ways of doing this some ways are:

Solution1:

n = [1,1,1,3,3,3,2,2,4,4,4,4,4,5,5,5,6,6,6,6,6,6,6,6,6]
def question_7_1(n):
    myCountDict = {}
    for i in n:
        countOfaNum = n.count(i)
        myCountDict[i] = countOfaNum
    print(myCountDict)

question_7_1(n)

Solution2: More effective and optimal:

a = [1,1,1,3,3,3,2,2,4,4,4,4,4,5,5,5,6,6,6,6,6,6,6,6,6]
d = {x:a.count(x) for x in a}
print(d)

Output:

{
 1: 3, 
 2: 2, 
 3: 3, 
 4: 5, 
 5: 3, 
 6: 9
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM