gpt4 book ai didi

python在列表中计数重复

转载 作者:行者123 更新时间:2023-12-03 22:54:08 25 4
gpt4 key购买 nike

我有这个 list :

['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', 'New York Giants', 'St. Louis Cardinals', 'Detroit Tigers', 'New York Yankees', 'New York Yankees', 'New York Yankees', 'New York Yankees', 'Cincinnati Reds', 'New York Yankees', 'St. Louis Cardinals', 'New York Yankees', 'St. Louis Cardinals', 'Detroit Tigers', 'St. Louis Cardinals', 'New York Yankees', 'Cleveland Indians', 'New York Yankees', 'New York Yankees']

我如何从这个列表中删除重复的 不使用 count、append 或 set 方法或导入 ?

或者我真正想要的是:我怎样才能把这个列表打印出来:
Boston Americans 5
New York Giants 2
team_name number_of_duplicates
team_name number_of_duplicates
team_name number_of_duplicates

最佳答案

要计算列表中每个条目的数量,您可以使用 Counter collections 中的类模块:

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', 'New York Giants', 'St. Louis Cardinals', 'Detroit Tigers', 'New York Yankees', 'New York Yankees', 'New York Yankees', 'New York Yankees', 'Cincinnati Reds', 'New York Yankees', 'St. Louis Cardinals', 'New York Yankees', 'St. Louis Cardinals', 'Detroit Tigers', 'St. Louis Cardinals', 'New York Yankees', 'Cleveland Indians', 'New York Yankees', 'New York Yankees']

from collections import Counter
c = Counter(l)
print(c)
c然后是 Counter对象,它保存列表中每个不同条目/键的出现次数。如 Counter源自 dict ,您可以像访问任何其他字典一样访问它。
Counter({'New York Yankees': 13, 'St. Louis Cardinals': 6, 'Philadelphia Athletics': 5, 'New York Giants': 4, 'Boston Red Sox': 4, 'Chicago White Sox': 2, 'Pittsburgh Pirates': 2, 'Detroit Tigers': 2, 'Cincinnati Reds': 2, 'Cleveland Indians': 2, 'Chicago Cubs': 2, 'Boston Americans': 1, 'Boston Braves': 1, 'Washington Senators': 1})

关于python在列表中计数重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27283874/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com