📜  Python – Counter.items()、Counter.keys() 和 Counter.values()

📅  最后修改于: 2022-05-13 01:54:22.961000             🧑  作者: Mango

Python – Counter.items()、Counter.keys() 和 Counter.values()

计数器类是 Python3 中的集合模块提供的一种特殊类型的对象数据集。 Collections 模块为用户提供了专门的容器数据类型,因此,提供了 Python 通用内置函数(如字典、列表和元组)的替代方案。 Counter 是一个子类,用于对可散列对象进行计数。它在调用时隐式创建一个可迭代的哈希表。

Counter.items()

Counter.items() 方法有助于查看列表中的元素以及它们在元组中各自的频率。

例子 :

Python3
# importing the module
from collections import Counter
 
# making a list
list = [1, 1, 2, 3, 4, 5,
        6, 7, 9, 2, 3, 4, 8]
 
# instantiating a Counter object
ob = Counter(list)
 
# Counter.items()
items = ob.items()
 
print("The datatype is "
      + str(type(items)))
 
# displaying the dict_items
print(items)
 
# iterating over the dict_items
for i in items:
    print(i)


Python3
# importing the module
from collections import Counter
 
# making a list
list = [1, 1, 2, 3, 4, 5,
        6, 7, 9, 2, 3, 4, 8]
 
# instantiating a Counter object
ob = Counter(list)
 
# Counter.keys()
keys = ob.keys()
 
print("The datatype is "
      + str(type(keys)))
 
# displaying the dict_items
print(keys)
 
# iterating over the dict_items
for i in keys:
    print(i)


Python3
# importing the module
from collections import Counter
 
# making a list
list = [1, 1, 2, 3, 4, 5,
        6, 7, 9, 2, 3, 4, 8]
 
# instantiating a Counter object
ob = Counter(list)
 
# Counter.values()
values = ob.values()
 
print("The datatype is "
      + str(type(values)))
 
# displaying the dict_items
print(values)
 
# iterating over the dict_items
for i in values:
    print(i)


输出 :

计数器.keys()

Counter.keys() 方法有助于查看列表中的唯一元素。

例子 :

Python3

# importing the module
from collections import Counter
 
# making a list
list = [1, 1, 2, 3, 4, 5,
        6, 7, 9, 2, 3, 4, 8]
 
# instantiating a Counter object
ob = Counter(list)
 
# Counter.keys()
keys = ob.keys()
 
print("The datatype is "
      + str(type(keys)))
 
# displaying the dict_items
print(keys)
 
# iterating over the dict_items
for i in keys:
    print(i)

输出 :

Counter.values()

Counter.values() 方法有助于查看每个唯一元素的频率。

例子 :

Python3

# importing the module
from collections import Counter
 
# making a list
list = [1, 1, 2, 3, 4, 5,
        6, 7, 9, 2, 3, 4, 8]
 
# instantiating a Counter object
ob = Counter(list)
 
# Counter.values()
values = ob.values()
 
print("The datatype is "
      + str(type(values)))
 
# displaying the dict_items
print(values)
 
# iterating over the dict_items
for i in values:
    print(i)

输出 :