在 Python 中计算列表中包含给定元素的子列表
pythonserver side programmingprogramming更新于 2026/1/22 15:40:17
给定列表中的元素也可以作为另一个变量中的另一个字符串出现。在本文中,我们将了解给定流在给定列表中出现的次数。
使用 range 和 len
我们使用 range 和 len 函数来跟踪列表的长度。然后使用 in 条件查找字符串作为列表中元素出现的次数。初始化为零的 count 变量在满足条件时不断递增。
示例
Alist = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
Bstring = 'Mon'
# 给定列表
print("给定列表:\n", Alist)
print("要检查的字符串:\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)
输出
运行上述代码得到以下结果 −
给定列表: ['Mon', 'Wed', 'Mon', 'Tue', 'Thu'] 要检查的字符串: Mon Number of times the string is present in the list: 2
使用 sum
我们使用 in 条件将字符串作为给定列表中的元素进行匹配。最后,只要匹配条件为正,就应用 sum 函数来获取计数。
示例
Alist = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
Bstring = 'Mon'
# 给定列表
print("给定列表:\n", Alist)
print("要检查的字符串:\n", Bstring)
count = sum(Bstring in item for item in Alist)
print("Number of times the string is present in the list:\n",count)
输出
运行上述代码得到以下结果 −
给定列表: ['Mon', 'Wed', 'Mon', 'Tue', 'Thu'] 要检查的字符串: Mon Number of times the string is present in the list: 2
使用 Counter 和 chain
itertools 和 collecitons 模块为服务提供了 chain 和 counter 函数,可用于获取列表中与字符串匹配的所有元素的数量。
示例
from itertools import chain
from collections import Counter
Alist = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
Bstring = 'M'
# 给定列表
print("给定列表:\n", Alist)
print("要检查的字符串:\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)
输出
运行上述代码得到以下结果 −
给定列表: ['Mon', 'Wed', 'Mon', 'Tue', 'Thu'] 要检查的字符串: M Number of times the string is present in the list: 2
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

