计算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 婆婆高寿祝福语大全简短