在本文中,我们给出了一个列表和一个字符串。我们需要查找给定字符串作为元素存在于列表中的次数。
来自collections模块的counter函数将为我们提供列表中每个元素的计数。从计数结果中,我们只能提取公平的那个指数,该指数与我们要搜索的元素的值匹配。
from collections import Counter Alist = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu'] elem = 'Mon' # Given list and element print("Given list:\n", Alist) print("Given element:\n",elem) cnt = Counter(Alist) print("Number of times the element is present in list:\n",cnt[elem])
输出结果
运行上面的代码给我们以下结果-
Given list: ['Mon', 'Wed', 'Mon', 'Tue', 'Thu'] Given element: Mon Number of times the element is present in list: 2
计数功能将给定流作为参数,并在给定列表中搜索该流。
Alist = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu'] elem = 'Mon' # Given list and element print("Given list:\n", Alist) print("Given element:\n",elem) cnt = Alist.count('Mon') print("Number of times the element is present in list:\n",cnt)
输出结果
运行上面的代码给我们以下结果-
Given list: ['Mon', 'Wed', 'Mon', 'Tue', 'Thu'] Given element: Mon Number of times the element is present in list: 2