Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
172 views
in Technique[技术] by (71.8m points)

Why One of the Arrays had an error checking when I tried to count the number of numbers in an array using python

So I tried to do something like counting how many occurances in an array and then saves those values on to Dictionary, but along the way there is one values that has wrong counts. When I did some tracing with the code I noticed that this value suddenly restarted the counting. Tried to search on the web but I didn't found it or I didn't search that deep.

Code :

listA = [11, 45, 8, 11, 101, 23, 45, 23, 45, 89, 101]
dictList = {
    
}

n = len(listA)

for i in range (0, n):
    total = 1
    if listA[i] not in dictList:
        dictList[listA[i]] = total
    else:
        for j in range (i, n):
            if listA[i] == listA[j]:
                total = total + 1
        dictList.update({listA[i] : total})

print(dictList)

The output it given :

{11: 2, 45: 2, 8: 1, 101: 2, 23: 2, 89: 1}

The correct output :

{11: 2, 45: 3, 8: 1, 101: 2, 23: 2, 89: 1}

Yes, it was just one variable that got wrong. Thank you in advance

question from:https://stackoverflow.com/questions/65867833/why-one-of-the-arrays-had-an-error-checking-when-i-tried-to-count-the-number-of

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here are several ways of counting elements in a list

list_to_count = [11, 45, 8, 11, 101, 23, 45, 23, 45, 89, 101]

# Basic dict operations
counts = {}
for x in list_to_count:
    if x not in counts:
        counts[x] = 1
    else:
        counts[x] += 1

# Using .get()
counts = {}
for x in list_to_count:
    counts[x] = counts.get(x, 0) + 1

# Using .setdefault()
# Pretty much the same as .get() but useful when the default is a mutable object like a list or dict
counts = {}
for x in list_to_count:
    counts[x] = counts.setdefault(x, 0) + 1

# Using collections.Counter (the simplest solution...)
from collections import Counter
counts = Counter(list_to_count)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...