给定列表中的元素也可以作为另一个字符串出现在另一个变量中。在本文中,我们将查看给定列表中给定流出现了多少次。
我们使用range和len函数来跟踪列表的长度。然后使用in条件查找字符串在列表中作为元素出现的次数。每当满足条件时,初始化为零的计数变量将保持递增。
Alist = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
Bstring = 'Mon'
# Given list
print("Given list:\n", Alist)
print("String to check:\n", Bstring)
count = 0
for i in range(len(Alist)):
if Bstring in Alist[i]:
count += 1
print("Number of times the string is present in the list:\n",count)输出结果
运行上面的代码给我们以下结果-
Given list: ['Mon', 'Wed', 'Mon', 'Tue', 'Thu'] String to check: Mon Number of times the string is present in the list: 2
我们使用in条件将字符串匹配为给定列表中的元素。最后,只要匹配条件为正,就应用求和函数获得计数。
Alist = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
Bstring = 'Mon'
# Given list
print("Given list:\n", Alist)
print("String to check:\n", Bstring)
count = sum(Bstring in item for item in Alist)
print("Number of times the string is present in the list:\n",count)输出结果
运行上面的代码给我们以下结果-
Given list: ['Mon', 'Wed', 'Mon', 'Tue', 'Thu'] String to check: Mon Number of times the string is present in the list: 2
itertools和collecitons模块为服务提供链和计数器功能,这些功能可用于获取与字符串匹配的列表中所有元素的计数。
from itertools import chain
from collections import Counter
Alist = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
Bstring = 'M'
# Given list
print("Given list:\n", Alist)
print("String to check:\n", Bstring)
cnt = Counter(chain.from_iterable(set(i) for i in Alist))['M']
print("Number of times the string is present in the list:\n",cnt)输出结果
运行上面的代码给我们以下结果-
Given list: ['Mon', 'Wed', 'Mon', 'Tue', 'Thu'] String to check: M Number of times the string is present in the list: 2