📌  相关文章
📜  计算列表中每个项目的数量python(1)

📅  最后修改于: 2023-12-03 15:28:00.195000             🧑  作者: Mango

计算列表中每个项目的数量

在编程中,有时需要对列表中的每个项目进行计数。Python提供了很多方式来实现这个功能。

方法一:使用循环遍历列表

这是最基本的方法。使用循环遍历列表,并使用计数器变量来跟踪每个项目的数量。

my_list = ['apple', 'banana', 'apple', 'orange', 'banana', 'pear']

count_dict = {}

for item in my_list:
    if item in count_dict:
        count_dict[item] += 1
    else:
        count_dict[item] = 1

print(count_dict)

这将产生以下输出:

{'apple': 2, 'banana': 2, 'orange': 1, 'pear': 1}
方法二:使用collections库

Python的标准库collections包含一个Counter类,可以用于计数。

from collections import Counter

my_list = ['apple', 'banana', 'apple', 'orange', 'banana', 'pear']

count_dict = dict(Counter(my_list))

print(count_dict)

这将产生以下输出:

{'apple': 2, 'banana': 2, 'orange': 1, 'pear': 1}
方法三:使用numpy库

Numpy库是用于数组计算的Python库。

import numpy as np

my_list = ['apple', 'banana', 'apple', 'orange', 'banana', 'pear']

unique, counts = np.unique(my_list, return_counts=True)

count_dict = dict(zip(unique, counts))

print(count_dict)

这将产生以下输出:

{'apple': 2, 'banana': 2, 'orange': 1, 'pear': 1}

无论使用哪种方法,都可以计算列表中每个项目的数量。选择使用哪种方法取决于您的具体情况和偏好。