计算lis中发生次数的另一种方法

2024-04-24 22:56:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个清单:

['Boston Americans', 'New York Giants', 'Chicago White Sox', 'Chicago Cubs', 'Chicago Cubs', 'Pittsburgh Pirates', 'Philadelphia Athletics', 'Philadelphia Athletics', 'Boston Red Sox', 'Philadelphia Athletics', 'Boston Braves', 'Boston Red Sox', 'Boston Red Sox', 'Chicago White Sox', 'Boston Red Sox', 'Cincinnati Reds', 'Cleveland Indians', 'New York Giants', 'New York Giants', 'New York Yankees', 'Washington Senators', 'Pittsburgh Pirates', 'St. Louis Cardinals', 'New York Yankees', 'New York Yankees', 'Philadelphia Athletics', 'Philadelphia Athletics', 'St. Louis Cardinals', 'New York Yankees']

假设我想计算"Boston Americans"在列表中的次数。你知道吗

如果不使用.count方法list.count("Boston Americans")或任何导入,我怎么做呢?你知道吗


Tags: newredbostonwhiteyorksoxchicagophiladelphia
3条回答

还有一种使用sum的方法:

sum( x==value for x in mylist )

这里,我们使用的事实是TrueFalse可以被视为整数0和1。你知道吗

数数:)

count = 0
for item in items:
    if item == 'Boston Americans':
        count += 1
print count

您可以使用内置的^{}函数:

>>> l=['Boston Americans', 'New York Giants', 'Chicago White Sox', 'Chicago Cubs', 'Chicago Cubs', 'Pittsburgh Pirates', 'Philadelphia Athletics', 'Philadelphia Athletics', 'Boston Red Sox', 'Philadelphia Athletics', 'Boston Braves', 'Boston Red Sox', 'Boston Red Sox', 'Chicago White Sox', 'Boston Red Sox', 'Cincinnati Reds', 'Cleveland Indians', 'New York Giants', 'New York Giants', 'New York Yankees', 'Washington Senators', 'Pittsburgh Pirates', 'St. Louis Cardinals', 'New York Yankees', 'New York Yankees', 'Philadelphia Athletics', 'Philadelphia Athletics', 'St. Louis Cardinals', 'New York Yankees']
>>> sum(1 for i in l if i=="Boston Americans")
1
>>> sum(1 for i in l if i=='Boston Red Sox')
4

相关问题 更多 >