简体   繁体   中英

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

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

From the collections.Counter() document:

A Counter is a dict subclass for counting hashable objects.

Hence you can iterate on Counter using dict.items() to get key and values together. For example:

lst = [1, 2, 3, 1, 2, 2, 2, 2, 2, 2]

for i, j in Counter(lst).items():
    print(i, j)

# Prints:    
#   1 2
#   2 7
#   3 1

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