计算Python列表中包含给定元素的子列表
给定列表中的元素也可以作为另一个字符串出现在另一个变量中。在本文中,我们将查看给定列表中给定流出现了多少次。
随着范围和镜头
我们使用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
热门推荐
10 毛笔哥哥结婚祝福语简短
11 向国庆送祝福语简短
12 建队节祝福语简短
13 朋友喜得外孙简短祝福语
14 小店营业的祝福语简短
15 餐饮生日祝福语简短独特
16 鲜花英语祝福语卡片简短
17 男朋友暴富祝福语简短
18 婶婶拜年祝福语大全简短