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



我有这个:

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:valuecounters,你使用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

最新更新