[英]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.