如何使用给定列表中的计数器查找特定键的值

How to find the value of a specific key using counter in the given list

我有给定的列表,我想通过使用集合中的计数器来访问我在列表中获得值“6”的次数:

list1=[3,4,6,4,5,6,2,3,6,7,6]
print("the number of time 6 occurred is ")
print(s6) #s6 is the variable to hold the number of time 6 occurred in the list. 

试试这个:

list1=[3,4,6,4,5,6,2,3,6,7,6]
print("the number of time 6 occurred is ")
s6 = 0
for i in list1:
  if i == 6:
    s6 += 1
print(s6)

使用Counter:

from collections import Counter

list1 = [3,4,6,4,5,6,2,3,6,7,6]
s6 = Counter(list1)[6]
print("the number of time 6 occurred is ")
print(s6)

但是请注意,您也可以简单地使用 count() 来计算列表中元素的出现次数:

s6 = list1.count(6)
s6 = Counter(list1)[6]

首先,使用 Counter 函数获取列表中出现的值的数量。键是元素,值是该值在列表中出现的次数。