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
97 views
in Technique[技术] by (71.8m points)

Accessing elements in Counter() in a loop python

I have this:

num_values = 3
lst = [1, 2, 3, 1, 2, 2, 2, 2, 2, 2]
counters = Counter(lst)

Counter({2: 7, 1: 2, 3: 1}) I need to do a for loop and access every value in my Counter. How do I do this? Example:

for value in counters:
    scores = 0
    if counters[key] <= num_keys:
        scores += 1

I'm getting wrong values with this and other tries too

question from:https://stackoverflow.com/questions/65857611/accessing-elements-in-counter-in-a-loop-python

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

1 Reply

0 votes
by (71.8m points)

Use like this way, it is basically going through key:value pair of counters, you used key without getting it. Also use num_values instead num_keys as there is nothing named num_keys in your code, you can use the value rather than again accessing by counters[key]. Another thing is you may be need to declare scores outside the loop.

scores = 0
for key, value in counters.items():
    # scores = 0
    if value <= num_values:
        scores += 1

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

...