【问题标题】:How to find the value of a specific key using counter in the given list如何使用给定列表中的计数器查找特定键的值
【发布时间】:2021-09-09 11:47:52
【问题描述】:

我有给定的列表,我想通过使用集合中的计数器来访问我在列表中获得值“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. 

【问题讨论】:

    标签: python python-3.x list collections counter


    【解决方案1】:

    使用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)
    

    【讨论】:

      【解决方案2】:
      s6 = Counter(list1)[6]
      

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

      【讨论】:

        【解决方案3】:

        试试这个:

        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)
        

        【讨论】:

        • OP想要使用Counter函数。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-28
        • 2012-12-12
        • 1970-01-01
        • 2023-01-07
        相关资源
        最近更新 更多