我有这个:
num_values = 3
lst = [1, 2, 3, 1, 2, 2, 2, 2, 2, 2]
counters = Counter(lst)
Counter({2: 7,1: 2,3: 1})我需要做一个for循环并访问Counter中的每个值。我该怎么做呢?例子:
for value in counters:
scores = 0
if counters[key] <= num_keys:
scores += 1
我得到错误的值与此和其他尝试也
像这样使用,它基本上是通过key:value
对counters
,你使用key
没有得到它。也使用num_values
代替num_keys
,因为在您的代码中没有名为num_keys
的东西,您可以使用value
而不是再次通过counters[key]
访问。另一件事是你可能需要在循环外声明scores
。
scores = 0
for key, value in counters.items():
# scores = 0
if value <= num_values:
scores += 1
来自collections.Counter()
文档:
因此,您可以使用Counter是
dict
的一个子类,用于计数可哈希对象。
dict.items()
迭代Counter
以获得键和值在一起。例如: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