Python 中统计列表中包含给定元素的子列表个数
给定列表中的元素也可能作为另一个字符串存在于另一个变量中。在本文中,我们将了解给定流在一个给定列表中出现的次数。
使用 range 和 len
我们使用 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
使用 sum
我们使用 in 条件来匹配给定列表中的字符串元素。最后应用 sum 函数来获取匹配条件为正时的计数。
示例
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
使用 Counter 和 chain
itertools 和 collections 模块提供了 chain 和 counter 函数,可用于计算与字符串匹配的列表中所有元素的个数。
示例
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
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP