简体   繁体   English

在循环中访问 Counter() 中的元素 python

[英]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. Counter({2: 7, 1: 2, 3: 1}) 我需要做一个 for 循环并访问我的 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.像这样使用,它基本上是通过key:value pair of counters ,你使用key却没有得到它。 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] .也使用num_values代替num_keys因为在您的代码中没有任何名为num_keys的内容,您可以使用该value而不是再次通过counters[key]访问。 Another thing is you may be need to declare scores outside the loop.另一件事是您可能需要在循环之外声明scores

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

From the collections.Counter() document:collections.Counter()文档:

A Counter is a dict subclass for counting hashable objects. Counter是用于计算可散列对象的dict子类。

Hence you can iterate on Counter using dict.items() to get key and values together.因此,您可以使用dict.items()Counter上进行迭代,以将放在一起。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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